Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 21st, 2012  |  syntax: None  |  size: 1.63 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Upload file directly to Content Database
  2. public static bool UploadFileToDocumentLibrary(string sourceFilePath, string targetDocumentLibraryPath)
  3.  
  4. {
  5.  
  6.     //Flag to indicate whether file was uploaded successfuly or not
  7.  
  8.     bool isUploaded = true;
  9.  
  10.     try
  11.  
  12.     {
  13.  
  14.         // Create a PUT Web request to upload the file.
  15.  
  16.         WebRequest request = WebRequest.Create(targetDocumentLibraryPath);
  17.  
  18.  
  19.  
  20.         //Set credentials of the current security context
  21.  
  22.         request.Credentials = CredentialCache.DefaultCredentials;
  23.  
  24.         request.Method = "PUT";
  25.  
  26.  
  27.  
  28.         // Create buffer to transfer file
  29.  
  30.         byte[] fileBuffer = new byte[1024];
  31.  
  32.  
  33.  
  34.         // Write the contents of the local file to the request stream.
  35.  
  36.         using (Stream stream = request.GetRequestStream())
  37.  
  38.         {
  39.  
  40.             //Load the content from local file to stream
  41.  
  42.             using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
  43.  
  44.             {
  45.  
  46.                 //Get the start point
  47.  
  48.                 int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
  49.  
  50.                 for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
  51.  
  52.                 {
  53.  
  54.                     stream.Write(fileBuffer, 0, i);
  55.  
  56.                 }
  57.  
  58.  
  59.  
  60.             }
  61.  
  62.         }
  63.  
  64.  
  65.  
  66.         // Perform the PUT request
  67.  
  68.         WebResponse response = request.GetResponse();
  69.  
  70.  
  71.  
  72.         //Close response
  73.  
  74.         response.Close();
  75.  
  76.     }
  77.  
  78.     catch (Exception ex)
  79.  
  80.     {
  81.  
  82.         //Set the flag to indiacte failure in uploading
  83.  
  84.         isUploaded = false;
  85.  
  86.     }
  87.  
  88.  
  89.  
  90.     //Return the final upload status
  91.  
  92.     return isUploaded;
  93.  
  94. }