Upload file to document library RRS feed

  • Question

  • Hi,

    I have trouble to upload a file to a document library in SharePoint 2010.
    The source file is located on a webserver, so I get it with a webrequest.
    The error I get is "A I/O error occurred" when I try to add the file to my library with SPFolder.Files.Add()

    using (Stream stream = webRequest.GetResponse().GetResponseStream())
        SPFile spFile = spFolder.Files.Add(fileName, stream, replaceExistingFiles);

    If I check the stream.Length it is 87629 bytes, so it is not empty.

    Any help is appreciated.


    Tuesday, June 25, 2013 10:44 AM


  • Hi Phrone,

    I just tested this out. Try the following code (reading the network stream into a memory stream is referenced from StackOverflow here:

    var webClient = new WebClient();
    using (Stream stream = webClient.OpenRead("http://someweb/request.xml"))
        if (stream == null) return;
        var buffer = new byte[16 * 1024];
        using (MemoryStream ms = new MemoryStream())
            int read;
            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                ms.Write(buffer, 0, read);
            SPContext.Current.Web.Files.Add("http://devmy101/documents/myfile.txt", ms, true);    

    Regards, Matthew
    My Blog
    Please remember to click "Mark As Answer" if a post solves your problem or "Vote As Helpful" if it was useful.

    I just added a webpart to the TechNet Gallery that allows administrative users to upload, crop and format user profile photos. Check it out here: Upload and Crop User Profile Photos

    • Edited by Matthew Yarlett Tuesday, June 25, 2013 1:03 PM Updated reference.
    • Marked as answer by Phrone Wednesday, June 26, 2013 1:11 PM
    Tuesday, June 25, 2013 1:02 PM