06 May 2011

Upload files to Share point from ASP.NET

We will see some of the code samples to upload files to a SharePoint or a mapped drive using HTTP PUT methods.
ASP.NET UI code is going to look something like
UI code

<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" Width = "500px" />
<br />
<br />
<asp:Button ID="UploadButton" runat="server" OnClick="Button1_Click"
Text="Upload File" />
<br />
<br />
<asp:Label ID="Label1" runat="server">asp:Label>
div>
form>
Upload Code
protected void UploadFileToSharePoint(string UploadedFilePath,
    string SharePointPath)
{
    WebResponse response = null;
    lnkUpload.Disabled = false;
    try
    {
        // Create a PUT Web request to upload the file.
        WebRequest request = WebRequest.Create(SharePointPath);

        request.Credentials = CredentialCache.DefaultCredentials;
        request.Method = "PUT";
        byte[] buffer = new byte[1024];
        using (Stream stream = request.GetRequestStream())
        using (FileStream fsWorkbook = File.Open(UploadedFilePath,
            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);
            }
        }

        response = request.GetResponse();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        response.Close();
    }
}
private void UploadFile()
{
    try
    {
        if (FileUpload1.HasFile)
            try
            {
                string uploadedFilePath = FileUpload1.PostedFile.FileName;
                Label1.Text = "File name: " +
                     FileUpload1.PostedFile.FileName + "
"
+
                     FileUpload1.PostedFile.ContentLength + " bytes
"
+
                     "Content type: " +
                     FileUpload1.PostedFile.ContentType;

                UploadFileToSharePoint(
                    uploadedFilePath ,
                    sharePointListPath + FileUpload1.FileName);
            }
            catch (Exception ex)
            {
                Label1.Text = "ERROR: " + ex.Message.ToString();
            }
        else
        {
            Label1.Text = "You have not specified a file.";
        }
    }
    catch (Exception)
    {
        throw;
    }
}
Delete file
    private void DeleteFile()
    {
    //bool isExists = false;
    System.IO.StreamReader reader = null;
    Stream dataStream = null;
    HttpWebResponse response = null;
    try
    {
        WebRequest request = WebRequest.Create(deleteFile);
        request.Credentials = new System.Net.NetworkCredential(USERNAME , PWD, DOMAIN);
        request.Method = "DELETE";
        response = (HttpWebResponse)request.GetResponse();
        dataStream = response.GetResponseStream();
        reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        // isExists = true;
    }
    catch (WebException)
    {
        throw;
    }
View Code 
private void OpenDoc()
{
    string loginUri = FILENAME   ;
    WebClient Client = new WebClient();
    Client.Credentials = new NetworkCredential(USERNAME , PWD, DOMAIN );
    byte[] b = Client.DownloadData(loginUri);
    HttpContext.Current.Response.AddHeader("content-disposition", "Attachment; filename=" + "Doc1.doc");
    HttpContext.Current.Response.BinaryWrite(b);
}
Check for File Exists
private bool CheckIfFileExists()
{
    bool isExists =false;
    System.IO.StreamReader  reader = null;
    Stream dataStream = null;
    HttpWebResponse response = null ;
    try
    {
        WebRequest request = WebRequest.Create(FILENAME);
        request.Credentials = new System.Net.NetworkCredential(USERNAME , PWD , DOMAIN );
        request.Method = "HEAD";
        response = (HttpWebResponse)request.GetResponse();
        dataStream = response.GetResponseStream();
        reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        isExists = true;
    }
    catch (WebException)
    {
        throw;
    }
    return isExists;
} 

4 comments:

Prajeesh Prathap said...

Jijo,

Would it be much better if we expose the methods as a separate service? Also it would be better if the methods are called from a different thread to improve user experience. What do you think?

Jijo Venginikkadan said...

Prajeesh,

Probably we are planning to expose as web service , not finalized.Thanks for your suggestions as threading part we did not tried.
Thanks for your comments.

Anonymous said...

Thanks... But one thing i realized after moving from Mphasis is, rather than being very technically good and writing code that is difficult for people to understand it's good to write simple and readable code that is human readable :).

Be Agile is the new Mantra. Btw nice to see that you are now constantly blogging. Keep doing it :)

Anonymous said...

I never thought I would agree with this option.