1 using System; 2 using System.Security.Permissions; 3 using Microsoft.SharePoint; 4 using Microsoft.SharePoint.Security; 5 using Microsoft.SharePoint.Utilities; 6 using Microsoft.SharePoint.Workflow; 7 using System.Web; 8 using System.IO; 9 10 namespace TestSharePointProject.DocEvent 11 { 12 /// <summary> 13 /// List Item Events 14 /// </summary> 15 public class DocEvent : SPItemEventReceiver 16 { 17 HttpContext currentContext; 18 public DocEvent() 19 { 20 currentContext = HttpContext.Current; 21 } 22 23 /// <summary> 24 /// An item is being added. 25 /// </summary> 26 public override void ItemAdding(SPItemEventProperties properties) 27 { 28 //将上载的文件URL按.分为两部分:URL和文件类型 29 string[] fileUrl = properties.BeforeUrl.Split('.'); 30 if (fileUrl.Length == 1) 31 { 32 properties.ErrorMessage = "文件类型不合法!"; 33 properties.Cancel = true; 34 } 35 else 36 { 37 //获取上载的文件类型 38 string postFix = fileUrl[fileUrl.Length - 1].ToLower(); 39 if (!postFix.Contains("xlsx") && !postFix.Contains("xls")) 40 { 41 properties.ErrorMessage = "请选择上传Excel文件!"; 42 properties.Cancel = true; 43 } 44 else { 45 if (currentContext != null) 46 { 47 if (currentContext.Request.Files.Count > 0) 48 { 49 //获取Item中被上传的所有文件 50 for (int i = 0; i < currentContext.Request.Files.Count; i++) 51 { 52 if (!string.IsNullOrEmpty(currentContext.Request.Files[i].FileName)) 53 { 54 FileStream file = null; 55 string path = currentContext.Request.Files[i].FileName.ToString(); 56 57 // Read the file. This appears to be the offending line 58 file = File.OpenRead(path); 59 byte[] Content = new byte[file.Length]; 60 file.Read(Content, 0, (int)file.Length); 61 file.Close(); 62 file.Dispose(); 63 //itemToAdd.Attachments.Add(currentContext.Request.Files[i].FileName, Content); 64 } 65 } 66 } 67 } 68 } 69 } 70 } 71 72 /// <summary> 73 /// An item is being updated. 74 /// </summary> 75 public override void ItemUpdating(SPItemEventProperties properties) 76 { 77 base.ItemUpdating(properties); 78 } 79 80 } 81 }