dayanrr91 dayanrr91 - 3 months ago 51
C# Question

Upload a file to sharepoint

I have a sharepoint account and I need to create a simple console application in c# that upload and download a file from a local folder to sharepoint, but I have no idea how to do that because I don't know anything about sharepoint, please give me some guide about where to start. thanks

Answer

you can do it using System.Net.WebRequest.
the example will use OpenFileDialog1 control to choose the file from local folder and upload it to sharepoint server (you can prompt the user to enter the path inside your console app).

please note: i wrote this code last month using VB.NET and converted it now to c#, the converter was doing a really lousy job so i converted most of it by hand and changed promt text from my mother tongue language - i cant test it now, but the original code i worte using visual basic is working perfect.

  • guiding comments are inside the code.

  • you need to connect from the local network and CredentialCache.DefaultCredentials are the client credantials.

another way to do that task is to use SOAP WebService i have added example in the bottom.

Upload file to sharepoint server using WebRequest:

private void UploadFileToSharePoint()
{
    string FileToUpload = null;
    string onlyfileName = null;
    string spcall = "use this field as your sub folder name on share point server (i am using sharepoint call number but you can use whatever you want";
    this.openFileDialog1.FileName = null;


    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        FileToUpload = this.openFileDialog1.FileName;
        onlyfileName = System.IO.Path.GetFileName(openFileDialog1.FileName);

        System.IO.FileInfo infoReader = default(System.IO.FileInfo);
        System.IO.FileInfo fInfo = new System.IO.FileInfo(FileToUpload);
        infoReader = fInfo;
        // 1000000 bytes = 10000 KB = 10 MB / restrict file size
        if (infoReader.Length > 10000000)
        {
            MessageBox.Show("file is to big");
            return;
        }

        UploadFileToSp(FileToUpload, spcall, onlyfileName);
    }
}

private void UploadFileToSp(string filepath, string spcall, string filename)
{

    if (UploadFileToSpSrv(spcall, filepath, filename) == true)
    {
        MessageBox.Show("the file was uploaded");
    }
}


public bool UploadFileToSpSrv(string spcall, string FilelocalPath, string FileName, int BufferSize = 4086)
{
    // EXAMPELS HOW THE PATES SHOULD BE:
    //'Dim uploadFilePath As String = "\\netapp2\xxx\xxx\xxx xxx\xxx\xxx\yyy.zzz"
    //'Dim SharePointListPath As String = "http://xxx/apps/misc/xxx/Lists/1/Attachments/8781/OrangeBilling.xlsm"
    //----------------------------------------------------------------------------------------------------------------------------------

    string SharePointListPath = "http://xxx/apps/misc/xxx/Lists/1/Attachments/" + spcall + "/" + FileName;
    string uploadFilePath = FilelocalPath;
    Uri finalPath = new Uri(SharePointListPath);

    WebResponse response = null;

    try
    {
        // Create a PUT Web request to upload the file.
        WebRequest request = WebRequest.Create(finalPath);

        request.Credentials = CredentialCache.DefaultCredentials;
        request.Method = "PUT";


        // Allocate a X KB buffer to transfer the file contents.
        // You can adjust the buffer size as needed, depending on
        // the number and size of files being uploaded.
        byte[] buffer = new byte[BufferSize + 1];

        // Write the contents of the local file to the
        // request stream.
        using (Stream stream = request.GetRequestStream())
        {
            using (FileStream fsworkbook = File.Open(uploadFilePath, FileMode.Open, FileAccess.Read))
            {
                int i = fsworkbook.Read(buffer, 0, buffer.Length);

                while (i > 0)
                {
                    stream.Write(buffer, 0, i);
                    i = fsworkbook.Read(buffer, 0, buffer.Length);
                }

            }
        }

        // Make the PUT request.
        response = request.GetResponse();
        return true;

    }
    catch (Exception ex)
    {

        return false;
    }
}

Upload file to sharepoint server using SOAP webservice:

  • you need to reference the webservice inside visual studio (the name i gave to the reference is oportal, and its the namespace of all webservice classes).
  • in order to reference a service right click on the project inside project explorer and choose Add Service Reference.
  • fileName is the file name to upload from the PC
  • spCall is the sharepoint ID number
  • you need to reference the name of your sharepoint list inside listService.AddAttachment() function.
  • the original code of this example was also written in vb.net and its working perfect. i converted it to c# but did not test it.

Getting Started With SharePoint Web Services

public bool AddAttachmentFile(string fileName, string spCall)
{
    oportal.Lists soap = new oportal.Lists();

    if (!File.Exists(fileName))
    {
        throw new ArgumentException(string.Format("file is not exist, filename: {0}", fileName));
    }

    FileStream fStream = File.OpenRead(fileName);
    string fname = fStream.Name.Substring(3);
    byte[] contents = new byte[fStream.Length + 1];
    fStream.Read(contents, 0, Convert.ToInt32(fStream.Length));

    fStream.Close();

    oportal.Lists listService = new oportal.Lists();
    listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
    listService.Url = "http://xxx/xxx/xxx/xxx/_vti_bin/Lists.asmx";

    try
    {
        string addAttach = listService.AddAttachment("the name of your list", spCall, fname, contents);
        return true;
    }
    catch (System.Web.Services.Protocols.SoapException ex)
    {
        return false;
    }

    }