今天发现了一个通过C#应用程序往SharePoint上传文件的方法。如下
1
static
void
Main(
string
[] args)
2 {
3 string _UploadedFilePath = " C:\\Documents and Settings\\bux\\Desktop\\TEST.PDF " ;
4 string _SharePointPath = " https://external1.collaboration.hp.com/external/RnD_Services/PRT/Job%20Proposal/JR.PDF " ;
5 UploadFileToSharePoint(_UploadedFilePath, _SharePointPath);
6 }
7
8 static void UploadFileToSharePoint( string UploadedFilePath, string SharePointPath)
9 {
10 WebResponse response = null ;
11
12 try
13 {
14 // Create a PUT Web request to upload the file.
15 WebRequest request = WebRequest.Create(SharePointPath);
16
17 request.Credentials = CredentialCache.DefaultCredentials;
18 request.Method = " PUT " ;
19
20 // Allocate a 1 KB buffer to transfer the file contents.
21 // You can adjust the buffer size as needed, depending on
22 // the number and size of files being uploaded.
23 byte [] buffer = new byte [ 1024 ];
24
25 // Write the contents of the local file to the
26 // request stream.
27 using (Stream stream = request.GetRequestStream())
28 using (FileStream fsWorkbook = File.Open(UploadedFilePath,
29 FileMode.Open, FileAccess.Read))
30 {
31 int i = fsWorkbook.Read(buffer, 0 , buffer.Length);
32
33 while (i > 0 )
34 {
35 stream.Write(buffer, 0 , i);
36 i = fsWorkbook.Read(buffer, 0 , buffer.Length);
37 }
38 }
39
40 // Make the PUT request.
41 response = request.GetResponse();
42 }
43 catch (Exception ex)
44 {
45 throw ex;
46 }
47 finally
48 {
49 response.Close();
50 }
51 }
2 {
3 string _UploadedFilePath = " C:\\Documents and Settings\\bux\\Desktop\\TEST.PDF " ;
4 string _SharePointPath = " https://external1.collaboration.hp.com/external/RnD_Services/PRT/Job%20Proposal/JR.PDF " ;
5 UploadFileToSharePoint(_UploadedFilePath, _SharePointPath);
6 }
7
8 static void UploadFileToSharePoint( string UploadedFilePath, string SharePointPath)
9 {
10 WebResponse response = null ;
11
12 try
13 {
14 // Create a PUT Web request to upload the file.
15 WebRequest request = WebRequest.Create(SharePointPath);
16
17 request.Credentials = CredentialCache.DefaultCredentials;
18 request.Method = " PUT " ;
19
20 // Allocate a 1 KB buffer to transfer the file contents.
21 // You can adjust the buffer size as needed, depending on
22 // the number and size of files being uploaded.
23 byte [] buffer = new byte [ 1024 ];
24
25 // Write the contents of the local file to the
26 // request stream.
27 using (Stream stream = request.GetRequestStream())
28 using (FileStream fsWorkbook = File.Open(UploadedFilePath,
29 FileMode.Open, FileAccess.Read))
30 {
31 int i = fsWorkbook.Read(buffer, 0 , buffer.Length);
32
33 while (i > 0 )
34 {
35 stream.Write(buffer, 0 , i);
36 i = fsWorkbook.Read(buffer, 0 , buffer.Length);
37 }
38 }
39
40 // Make the PUT request.
41 response = request.GetResponse();
42 }
43 catch (Exception ex)
44 {
45 throw ex;
46 }
47 finally
48 {
49 response.Close();
50 }
51 }