How to: Magic with SharePoint 2003, uploading files using a Web service


Some time ago I blogged about my intentions of uploading files to a SharePoint Document Library site from a local folder using some kind of Web service. After doing some research and some tests, I found a very easy way to do that and now I want to share with you the approach I followed since you might find it useful as well.


Prerequisites


To build this solution, you need to install Office SharePoint Portal Server 2003 and follow the next steps:



  • Create a Document Library
  • Grant access to the users that will upload files to the Document Library:

To install the Web service:



  1. Download ODC_WritingCustomWebServicesSampleSPPT.EXE.

  2. Extract the download contents to your hard drive and Run build.bat.

    • Note: This will install the Web service on the _vti_bin virtual directory inside the Default Web Site.

  3. Open the IIS Management Console (INETMGR) and navigate to the the _vti_bin virtual directory (inside the Default Web Site).
  4. Find SPFiles.asmx, right click, and Browse.
  5. Navigate to http://localhost/_vti_bin/SPFiles.asmx to validate if you have installed successfully the Web Service.

To consume the Web Service:



  1. From your managed application, add a reference to the http://localhost/_vti_bin/SPFiles.asmx Web Service.
  2. Call the Web service DocumentLoader
  3. Create a helper class to upload files. You can use the helper class I created.
    using System;
    using 
    System.Net;
    using 
    System.IO;
    using 
    System.Configuration;
    using 
    System.Text;
    using 
    System.Web;
    using 
    System.Security;
    using 
    System.Web.Security;
    using 
    System.Web.UI;
    using 
    System.Web.UI.WebControls;
    using 
    System.Web.UI.WebControls.WebParts;
    using 
    System.Web.UI.HtmlControls;
    using 
    DocumentLoader;

    /// <summary>
    /// A sample SharePointHelper class to upload files
    /// </summary>
    public class SharePointUploadHelper {
       
    private string _sharepointDocumentLibrary;

       public 
    SharePointUploadHelper() {
          _sharepointDocumentLibrary 
    ConfigurationManager.AppSettings[“SharePointDocLibrary”];
       
    }

       
    public string UploadDocumentsToSharePoint(string fileName) {

          DocumentLoader.SPFiles svcDocLoader 
    = new DocumentLoader.SPFiles();
          
    svcDocLoader.PreAuthenticate = true;
          
    svcDocLoader.Credentials CredentialCache.DefaultCredentials;

          string 
    strPath fileName;
          string 
    strFile strPath.Substring(strPath.LastIndexOf(“\\”) + 1);
          string 
    strDestination _sharepointDocumentLibrary;

          
    FileStream fStream = new FileStream(strPath, System.IO.FileMode.Open);
          byte
    [] binFile = new byte[(int)fStream.Length];
          
    fStream.Read(binFile, 0, (int)fStream.Length);
          
    fStream.Close();
          string 
    result svcDocLoader.UploadDocument(strFile, binFile, strDestination);

          return 
    (result);
       
    }
    }

  4. Create a Web Form, Win Form, or console application that will require a user to upload files.
     
  5. Call the UploadDocumentsToSharePoint method of the SharePointUploadHelper class, for example:
    protected void btnLoadFile_Click(object sender, EventArgs e)
        {
            SharePointUploadHelper fh 
    = new SharePointUploadHelper();
            string 
    serverTempFilePath Server.MapPath(@”/yourApplication”);
            
    contentFileUpload.PostedFile.SaveAs(serverTempFilePath);
            
    lblUploadResults.Text fh.UploadDocumentsToSharePoint(serverTempFilePath);
        
    }

  6. Open the configuration file (i.e. Web.config) and turn on impersonation.
    <identity impersonate=”true” />

  7. Add a configuration key that points to the SharePoint Document Library where you will upload files.
    <add key=”SharePointDocLibrary” value=”http://myServerName/myDocumentLibrary”/>

  8. Build your application
  9. Run and test the application, and there, a great web service.

I can tell you it works, just keep in mind the download is a code sample.


Enjoy!


-Erika

Comments (69)

  1. Tim says:

    Is this method appropriate for uploading large files (>20MB) into a Sharepoint DL?  I have tried this but do not think a web service is appropriate for large file uploads.  I think FTP would be better (but obviously you cannot use it to upload to a Sharepoint DL).

  2. Erika Ehrli says:

    Hi Tim,

    You might explore other alternatives if you plan to upload big files (>20MB). The biggest file I have uploaded using this Web service is about 2 MB.

    You know best practices are sometimes subjective, but I know that users should not upload files bigger than 2 MB while using a File Upload service. IIS and ASP.NET have a file size limitation.

    One thing you can do to upload bigger files, is modify the httRuntime maxRequestLength value inside your web.config file. For example, if you add this line of code…

    <httpRuntime maxRequestLength=”8192″/>

    to your Web.config file, you would allow users to upload files with a max length of 8 MB.

    I hope this helps…
    -Erika

  3. Tom Bizannes says:

    The non-technical people may find WISDOM Explorer part of WISDOM Document Management Framework works well with the larger files.

    It also prompts for meta tags etc

  4. Bob C says:

    Thanks Erika.  Great hint.

    And in VP.net, that would be:

      Public Function UploadDocumentsToSharePoint(ByVal fileName As String) As String

         Dim svcDocLoader As DocumentLoader.SPFiles =  New DocumentLoader.SPFiles()

         svcDocLoader.PreAuthenticate = True

         svcDocLoader.Credentials = CredentialCache.DefaultCredentials

         Dim strPath As String =  fileName

         Dim strFile As String =  strPath.Substring(strPath.LastIndexOf("\") + 1)

         Dim strDestination As String =  _sharepointDocumentLibrary

         Dim fStream As FileStream =  New FileStream(strPath,System.IO.FileMode.Open)

         Dim binFile() As Byte =  New Byte(CType(fStream.Length) {}, __0__)

         fStream.Read(binFile, 0, CType(fStream.Length, Integer))

         fStream.Close()

         Dim result As String =  svcDocLoader.UploadDocument(strFile,binFile,strDestination)

         Return (result)

      End Function

  5. Bob C says:

    Erika,

    I’ve tried to modify the code to use a string instead of a file.  I’m getting

    "Value does not fall within the expected range.Microsoft.SharePoint"

    Any ideas, or info on getting more about the error that’s occuring?

    Thanks in advance…

    /bac

       <WebMethod(Description:="Upload a file to a doc lib.  The web service App Setting SharePointDocLibrary sets the destination library.")> _

       Public Function UploadDocumentToSharePoint(ByVal asDocName As String, ByVal asdocumentContents As String) As String

           ‘ 20060601 R.Chauvin bob_chauvin@yahoo.com

           ‘ adapted from http://blogs.msdn.com/erikaehrli/archive/2006/05/04/SharePointUploadHelper.aspx?CommentPosted=true#commentmessage

           Dim svcDocLoader As DocumentLoader.SPFiles = New DocumentLoader.SPFiles()

           svcDocLoader.PreAuthenticate = True

           svcDocLoader.Credentials = CredentialCache.DefaultCredentials

           ‘Dim strPath As String = asdocumentContents

           ‘Dim strFile As String = strPath.Substring(strPath.LastIndexOf("\") + 1)

           Dim strDestination As String = _sharepointDocumentLibrary

           ‘Dim fStream As FileStream = New FileStream(strPath, System.IO.FileMode.Open)

           ‘Dim binFilex() As [Byte] = New Byte(CType(fStream.Length, Integer)) {}

           Dim binFile() As [Byte] = System.Text.Encoding.UTF8.GetBytes(asdocumentContents)

           ‘fStream.Read(binFile, 0, CType(fStream.Length, Integer))

           ‘fStream.Close()

           Dim result As String = svcDocLoader.UploadDocument(asDocName, binFile, strDestination)

           Return (result)

       End Function

  6. Bob C says:

    Interesting… If I use

    http://localhost/my site/forms/ I get a different error

    "The folder that would hold URL ‘Enterprise Contact Cleanup Form/Forms/’ does not exist on the server.Microsoft.SharePoint"

  7. Bob C says:

    Found the issue…  My url had a trailing /.  Removed that, and it worked for either localhost or server name.

    Sorry:)

  8. Bob C says:

    A simplified VB version that takes string as file contents.

       Public Function UploadDocumentToSharePoint(ByVal asDocName As String, ByVal asdocumentContents As String) As String

           ‘ 20060601 R.Chauvin bob_chauvin@yahoo.com

           ‘ adapted from http://blogs.msdn.com/erikaehrli/archive/2006/05/04/SharePointUploadHelper.aspx?CommentPosted=true#commentmessage

           Dim svcDocLoader As DocumentLoader.SPFiles = New DocumentLoader.SPFiles()

           svcDocLoader.PreAuthenticate = True

           svcDocLoader.Credentials = CredentialCache.DefaultCredentials

           ‘Dim strPath As String = asdocumentContents

           ‘Dim strFile As String = strPath.Substring(strPath.LastIndexOf("\") + 1)

           Dim strDestination As String = _sharepointDocumentLibrary

           Dim binFile() As [Byte] = System.Text.Encoding.UTF8.GetBytes(asdocumentContents)

           ‘Dim fStream As FileStream = New FileStream("c:tempASPNETSetup_00000.log", System.IO.FileMode.Open)

           ‘Dim binFilex() As [Byte] = New Byte(CType(fStream.Length, Integer)) {}

           ‘fStream.Read(binFilex, 0, CType(fStream.Length, Integer))

           ‘fStream.Close()

           Dim result As String = svcDocLoader.UploadDocument(asDocName, binFile, strDestination)

           Return (result)

       End Function

  9. Karthik says:

    I am getting the following error: "The folder that would hold URL ‘sites/projects/myproject/project%documents/forms’ does not exist on the server.Microsoft.SharePoint". i have given the following key in web.config file. "http://myserver/sites/projects/myproject/Project%20Documents/forms&quot;

  10. CNatra says:

    Would it be possible to upload a file overwriting the existing one and thus mantaining the versioning?

    Thanks in advance

  11. Bob C says:

    A new error:

    The folder that would hold URL ‘sites/EntContacts/shared documents’ does not exist on the server.Microsoft.SharePoint"

  12. erikaehrli says:

    Bob and Karthik,

    I remember getting this error too. I am using a document library on the default site:

    <add key="SharePointDocLibrary" value="http://myserver/myDocLibrary"/&gt;

    I have not tried using the service with document libraries inside sites, let me run some tests and I will let you know if I was able to make this work.

  13. Bob C says:

    Thanks Erika,

    Yes, I created a form lib off the default site and it works, but not off sub site doc libs.

    Also,  Any idea as to wether this will work with V3?

  14. Bob_Chauvin says:

    And as CNatra asked, How can we handle versions?  I’ll experiment with check out/in, but if you (Erika) know better.

    Or, can we get the source to the .dll and extend it?

  15. Bob_Chauvin says:

    Another interesting blog with some hints…

    http://www.sharepointblogs.com/rcragg/archive/2004/05/25/482.aspx

  16. Bob_Chauvin says:

    Turned out that adding the ability to support overwrite/versioning was as simple as modifying the spfiles.asmx.cs and changing the add method to use the override parameter.

    Still working on the issue of using a doc lib in a sub-site.

  17. Bob_Chauvin says:

    See my follow-up post here:

    http://programteama.blogspot.com/

  18. walterd says:

    Hi

    I installed the Web Service and could browse it. The service will be called by Metastorm e-Work. How can I authenticate the user from within the WebService and send the credentials to SharePoint if Metastorm e-Work only sends me the DomainNameUserName?

    Your help is highly appreciated.

  19. Kevin says:

    Great post many thanks. I am having a slght problem when i try to run the application i get the following string as a result:

    "Object reference not set to an instance of an object .WSCheckout"

    any ideas?

    Thanks in advance

    Kevin

  20. Kevin says:

    Morning(well in this part of the world), still having the same problem but have a bit more on the error:

    System.NullReferenceException: Object reference not set to an instance of an object.

    at WSCheckOut.SPFiles.GetFile(string fileUrl)

    at WSCheckout.SPFiles.Checkout(String fileUrl)

    any advice or help would be much appreciated

    Thanks Again,

    Kevin

  21. BobC says:

    So,

    When this code executes, what do you see for the svcDocLoader?  

    Your app should have a web reference to the class, so make sure you read the instructions…

    DocumentLoader.SPFiles svcDocLoader = new DocumentLoader.SPFiles();

  22. Kevin says:

    Thanks for your response. Im running pretty much your code inside a main method of a console app:

    static void Main(string[] args)

    {

    DocumentLoader.SPFiles svcDocLoader = new DocumentLoader.SPFiles();

    svcDocLoader.PreAuthenticate = true;

    svcDocLoader.Credentials = CredentialCache.DefaultCredentials;

    string strPath = "test.doc";

    string strFile = strPath.Substring(strPath.LastIndexOf("\") + 1);

    string strDestination = "http://localhost/Shared Documents";

    FileStream fStream = new FileStream(strPath, System.IO.FileMode.Open);

    byte[] binFile = new byte[(int)fStream.Length];

    fStream.Read(binFile, 0, (int)fStream.Length);

    fStream.Close();

    string result = svcDocLoader.UploadDocument(strFile, binFile, strDestination);

    Console.WriteLine(result);

    }

    I have the web ref alright and when i access it through a browser i can see all the methods

    CheckIn

    CheckOut

    etc

    However, if i try to invoke any of them i get that error message:

    System.NullReferenceException: Object reference not set to an instance of an object.

    at WSCheckOut.SPFiles.GetFile(string fileUrl)

    at WSCheckout.SPFiles.Checkout(String fileUrl)

    any ideas?

    Cheers again,

    Kevin

  23. BobC says:

    Did you run the bat file to build/deploy the object from the MS site?  Perhaps you can send a screen shot of your solution explorer with the web reference expanded…  Just for giggles.

  24. BobC says:

    Also, are you able to debug?  If so, you can check to see if it’s the WSCheckOut.SPFiles that is null, or the fileURL.

  25. Kevin says:

    Yep i ran the bat file. However(here is the point where u start to say "ahha" i hear:) i changed:

    set CSC="%WINDIR%Microsoft.NetFrameworkv1.1.4322csc.exe"

    to

    set CSC="%WINDIR%Microsoft.NetFrameworkv2.0.50727csc.exe"

    and(drum roll)..

    set WSEDIR="%COMMONPROGRAMFILES%Microsoft SharedWeb Server Extensions60ISAPI"

    to

    set WSEDIR="%COMMONPROGRAMFILES%Microsoft SharedWeb Server Extensions12ISAPI"

    because im trying to implement this on wss v3.. which also has no bin directory by defualt in _vti_bin

    ill post a screen shot of my web refrence though when i can get into my webspace probably a few hours time.

    i really would love to be able to get this working in 3 if its possible

    Thanks again(and i hope ur not too mad that i was kind holding back on the v3 part;) thought it might make u runaway;)

    We’re looking into a switch from our current document M system to wss and we’re using the beta as a sandbox to bascially familirse are selves with wss and get some testing on document migration and customisation done.

    cheers yet again,

    Kevin

  26. Kevin says:

    oh and i reckon its WSCheckOut.SPFiles thats null as ive also hardcoded the fileurl into the webmethods and still the same error.

  27. BobC says:

    No worries.  

    I will also be working on the v3 implementation of this…  I think it should work, as the wssv3 sdk indicates the methods used are available.

    Keep me posted as to your progress.

  28. BobC says:

    It looks like the Sharepoint_app_bin folder is where this should now go, as the STSSOAP.DLL has moved there.

    You may want to post to the Sharepoint v3 beta newsgroup to verify this…

  29. Kevin says:

    cool ill give it ago. cheers for all help ill let you know how i get on :) have a good weekend

    Kevin

  30. sona says:

    i am getting this error, when i create the healperclass

    The type or namespace name ‘DocumentLoader’ could not be found (are you missing a using directive or an assembly reference?)

    any advice or help would be much appreciated, thank you

  31. Joe Haviland says:

    What do I have to do to get this running with SharePoint 2007?  With a few changes, it compiles.  But, I can’t add a web reference to it in a C# project.

  32. Bob says:

    Can you run this in your WSS v2 setup?  The process should be quite the same.  Can you give us more details, post some screen shots?

  33. Joe Haviland says:

    Problem resolved.  Rather than using the BAT file, I created a Web Service project in VS 2005 and a new disco was created.

  34. Alexander says:

    Listen, people! If someone have make it works (i mean this web service for MOSS 2007), PLEASE, let others know HOW. Anyone? That would be great! Thanks.

  35. Bob_Chauvin says:

    I did get this working on V3, with one exception.  The column promotion on SPPS isn’t working for the Infopath Form I’m uploading…

  36. Steve says:

    How would you go about preserving the original author names and creation dates for uploaded files.  I know this is very difficult in WSS V2, but maybe there is a better way in WSS V3?

  37. Steve says:

    How would you go about preserving the original author names and creation dates for uploaded files.  I know this is very difficult in WSS V2, but maybe there is a better way in WSS V3?

  38. sathish says:

    Hi,

    when i try to upload documents into subsites

    I am getting the following error:

    "The folder that would hold URL ‘sites/subsiteone/sampleDocLib’ does not exist on the server.Microsoft.SharePoint".

    Does anyone of you have solution to this.

    I think Bob and Kartik for the same error before.Did anyone of you resolved it.

  39. BobC says:

    Steve:

    Re original author names, in v3 versioning along with a minor code change SHOULD take care of this ,per my prior post.

    Also, I spoke with MS Support about Infopath field promtion in doc libs v3 and it DOES work..

    Satish:

    The web service has to be on the same server as Sharepoint.  Try debugging…

  40. sunny says:

    hi

    i see few steps not present in 2007,

    missing bin folder isn ispai folder,

    2) i a have a web service which creates subsites and sites and am stoeing the infomationin config file  or xml and am readin git. wher to delpoy this new xml file and  wher ero delpoy the dll.

    thanks sunil

  41. BobC says:

    Trying to set this up on another server, now this runtime error trying to create the web reference…

    Could not create type ‘WSCheckOut.SPFiles’.

    I CAN view the ?WSDL and ?DISCO, but when it comes time to create the object… BOOM!

    I’ll be back-tracking, but any advice would be nice…

  42. Brian says:

    Has anyone done this with a windows app?  I’m getting a bunch of errors when i try to copy the Helper class she wrote into a windows, obviously system.web.ui isn’t going to work, I have to change the Using directives along with the config file settings, Anyone else do this in a win form yet?

  43. BobC says:

    Brian,

    You can CALL this web service from a windows app.  In Visual Studio 2005 you create a web reference, initialize a variable of the type, set your credentials, and go.

    You cannot insert the code from the sample in a winform, because it needs to run in the context of SharePoint.

    Start by getting the service working as described and build out from there.

  44. Ze Wen Oh says:

    Hello,

    Is it possible to display the document files inside the sharepoint "Document Library" using web service??? Someone, please help me…

    Ze Wen Oh

  45. bharat says:

    hi gud job but i have another windows services through which i can send till 63 mb but i am getting an error for a file bigger than 64 or 65

    any help guys my max request was 1 mb

  46. Digital_Damage says:

    Anyone get this to work with subsites?

    getting

    "The folder that would hold URL ‘sites/subsiteone/sampleDocLib’ does not exist on the server.Microsoft.SharePoint".

  47. BobC says:

    Dear Damage,

    Yes, this does work for sub-sites.  

    Are you running on WSSv2 or v3?  The approach is a bit different for each.  Check out this link for details. http://groups.google.com/group/microsoft.public.sharepoint.windowsservices.development/browse_frm/thread/37a2a5ef6d5dd86c/?hl=en#

    Here is some sample v3 code:

    fileUrl = fileUrl.ToLower();

                   if (fileUrl.Length > 0)

                   {

                       ls_fileURL = fileUrl.Replace("http://&quot;, "").Replace("localhost/", "").Replace("my.wsssitename.com/", "");

                       ls_fileURLParts = ls_fileURL.Split(new Char[] { ‘/’ }); //, StringSplitOptions.RemoveEmptyEntries

                       for (int i = 0; i < (ls_fileURLParts.Length – 2); i++)

                       {

                           // all but the last two elements ie "sites/EntContacts"

                           if (ls_fileURLParts[i] == "") continue;

                           ls_SourceSiteName = ls_SourceSiteName + "/" + ls_fileURLParts[i];

                       }

                       SPSite siteCollection = SPControl.GetContextSite(Context);

                       SPWeb srcSite = siteCollection.AllWebs[ls_SourceSiteName];//"Source_Site_Name"];

                       // Determine the Folder and File name

                       //eg "EnterpriseContacts/Form5.xml";

                       // The folder and file are the last two sections of the url.

                       ls_SourceFolder = ls_fileURLParts[ls_fileURLParts.Length – 2] + "/" + ls_fileURLParts[ls_fileURLParts.Length – 1];

                       SPFile srcFile = srcSite.GetFile(ls_SourceFolder);//"Source_Folder_Name/Source_File");

  48. Sumith Jacob Chacko says:

    Is there any way to debug a webservice, deployed on SharePoint V3 deployed on win 2003 machine, using .Net 2005?

    -> Generated the dll & pdb for the webservice.

    -> Copied the dll n the pdb to app_bin folder of my sharepoint site.

    Proj Settings":

    -> In PropertyPages – StartOptions -selected- "Dont Open a page. Wait for request from external application"

    -> In PropertyPages – StartOptions -selected- "UseCustomServer" and specified the site address that would be given in browser to get the site.

    While running the debugger I get following error – "Unable to start debugging on the web server. The web server is not configured correctly. see help for…."

    I see that in the web.config there is an element "<compilation batch="false" debug="false">". I am reluctant to change debug to "true" as it had led to site crash earlier.

    Would appreciate any pointers given to get me start debugging the webservice..

  49. BobC says:

    You need to pursue the debugging.  If this is a production site, set up another stand-alone dev server for testing.

  50. JH says:

    Can anyone please post a complete sample in zip for WSS v3? I saw many people worked it out but it seems we dont have a complete updated version of sample.

    Thanks a lot!

    JH

  51. This is more for my benefit because I always seem to have to research this over and over and over again,

  52. Willy says:

    Hi,

    To make this work with subsites just add the web reference using subsites URL.

    ie: http://servername/subsitename/_vti_bin/SPFiles.asmx

    cheers :)

  53. Mike says:

    How do you modify the override parameter to over write existing files of the same name? I have this line currently…

    SPFile file = folder.Files.Add(fileURL, fileContents, true);

  54. Thamizh says:

    Hello

    I am encountering a problem finding .asmx file. Here the SharePoint was installed recently but this server is in use by other departments. This is the 1st web application I’m trying out here. In IIS, Default website is set to Stop and a Test website contains all my projects although I don’t remember creating one. There are 2 other websites

    1. SharePoint – 80(runs on port 80),

    2. SharePoint – 24184(runs on port 24184)

    Both these contain _vti_bin folders. I ran a setup that installed .asmx file in _vti_bin folder. Now I try to find that file but it is not in these _vti_bin folders.

    Could you please help me figure out what’s wrong here?

    Struggling for the past half a day doing various permutations and combinations copying and pasting files….

    Any help will be highly helpful

    Thanks

    Thamizh

  55. Gopala Krishna says:

    Hello Erika,

    I am working on uploading and downloading a document through WSS. Everything is working fine but i am struck at setting the value of document custom field.

    Any idea of how to achieve this?

    thanks in advance.

    -gopal

  56. Gopala Krishna says:

    Hi, i found it myself…..

    SPFile myfile = site.Files.Add(destUrl,fileContent);

    SPListItem myitem = myfile.Item;

    myitem["File Name"]= "xyz";

    myitem.Update();

    -gopal

  57. S.D. says:

    Gopala,

    I’m trying your code and cannot seem to get it working.

                   SPSite site = new SPSite("http://ussrm-wsf:25594/Docs/default.aspx&quot;);

                   SPWeb web = site.OpenWeb();

                   //string col1 = "cheeseburger";

                   SPFolder objFolder = myWeb.GetFolder("IBM Reports");

                   string fileURL = fileName;

                   byte[] myFile = new byte[1000];

                   FileStream mystream = new System.IO.FileStream(strFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);

                   mystream.Read(myFile, 0, 1000);

                   mystream.Close();

                   SPFile file = folder.Files.Add(fileURL, fileContents, true);

                   SPListItem myitem = file.Item;

                   myitem["WSF2_ID"] = "xyz";

                   myitem.Update();

    It uploads fine, but the custom fields are always blank. Did you have to do anything on the document library side for this to work?

  58. Free SharePoint Web Parts (3rd Party) Konrad Brunner – UGS&#39;s Web Parts (broken link 8/25) Document

  59. Patrick Niezen says:

    Hi everyone,

    I’ve been struggling for some days now trying to get this working on a secured SharePoint Server 2003. Here’s the solution that worked for me.

    1) Change the credentials in the helperclass:

      service.Credentials = new NetworkCredential("username", "password");

    2) In the web.config file on the server change the trustlevel to:

      <trust level="WSS_Medium" originUrl=".*" />

    Just wanting to share this with you guys, might help you out.

  60. Michael Mann says:

    When i browse the SPFiles.asmx from IIS

    I get the error

    Could not create type  WSCheckOut.SPFiles

  61. Selebogo says:

    MOSS 2007

    I am trying to Check in a document after Editing its properties and get the following error :

    Value does not fall within the expected range

  62. Jan says:

    Erika,

    I used your file upload sample and followed your instructions for installation.

    I run sharepoint on port 81.

    This is the code I use to upload a generated excel document.

               WSS_UPLOAD.SPFiles SharePointUploadService = new global::EXCELconnector.WSS_UPLOAD.SPFiles();

               SharePointUploadService.Url = "http://10.0.0.11:81/_vti_bin/SPFiles.asmx&quot;;

              SharePointUploadService.PreAuthenticate = true;

              SharePointUploadService.Credentials = new System.Net.NetworkCredential("administrator", "1616xn152", "mammoth");

              System.IO.FileStream fStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open);

              byte[] binFile = new byte[(int)fStream.Length];

              fStream.Read(binFile, 0, (int)fStream.Length);

              fStream.Close();

              SharePointUploadService.UploadDocument(fileName, binFile, "Cherubim", null);

    On the UploadDocument call I receive the following exception:

    System.Web.Services.Protocols.SoapException was unhandled

     Message="Server was unable to process request. —> Request for the permission of type ‘Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c’ failed."

     Source="System.Web.Services"

     Actor=""

     Lang=""

     Node=""

     Role=""

     StackTrace:

          at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)

          at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)

          at EXCELconnector.WSS_UPLOAD.SPFiles.UploadDocument(String fileName, Byte[] fileContents, String targetFolder, String targetWebSiteOverride)

          at EXCELconnector.EXCELsink.PutRow(XmlNode row)

          at CherubimExchange.processSequence.Execute() in C:Prisma.Expirimenten.dotnet2CherubimExchangeServiceCherubimSourceConnectorHeartBeat.cs:line 144

          at CherubimExchange.TaskDef.Execute() in C:Prisma.Expirimenten.dotnet2CherubimExchangeServiceCherubimSourceConnectorTaskDef.cs:line 25

          at CherubimExchange.TaskDef.TaskDefCallBack(Object stateInfo) in C:Prisma.Expirimenten.dotnet2CherubimExchangeServiceCherubimSourceConnectorTaskDef.cs:line 134

          at System.Threading._TimerCallback.TimerCallback_Context(Object state)

          at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

          at System.Threading._TimerCallback.PerformTimerCallback(Object state)

    Any clue?

  63. Piyush says:

    Jan,

    Were you able to solve the security issue? I am facing the same issue. Please help if you have solution.

  64. Raj says:

    Getting the error: "Value does not fall within the expected range.Microsoft.SharePoint"

    void UploadFilesToSharepoint(HttpFileCollection files)

    {

    uploadservice = new Uploadwebsrv.SPUploadFiles();

    uploadservice.PreAuthenticate = true;

    uploadservice.Credentials = GetNetworkCredential();

    uploadservice.Timeout = 1000000;

    for(int i=0; i<files.Count; i++)

    {

    string fileName = Path.GetFileName(files[i].FileName);

    Stream fstream = files[i].InputStream;

    byte[] fbytes = new byte[fstream.Length];

    fstream.Read(fbytes, 0, fbytes.Length);

    fstream.Close();

    targetFolderPath = ConfigurationSettings.AppSettings["TargetFolder"].ToString();

    try

    {

    if (fileName!=null && fileName.Length>0)

    {

    string result = uploadservice.UploadDocument(fileName,fbytes,targetFolderPath);

    }

    }

    catch (Exception ex)

    {

    //LogMessages(MessageType.Exception, ex.ToString(), "TotalFiles:" + files.Count.ToString());

    }

    }

    }

    any ideas?

  65. Gourav jain says:

    When I am Running this whole webservice with the class i am getting a error that "Access to the path "F:taskExpensesGourav.txt" is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String str) at System.IO.FileStream" the path it is showing is the one from where i want to upload the file..

    please tell me the solution asap…..

  66. Ben Herman says:

    For an example of uploading via FrontPage RPCs please see http://www.benherman.com/ftp/copy-sp.ps1.

    Ben