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;
} 

Storing Uploaded Files in a Database or in the File System

There was a requirement in one of our project where we need to upload document from .NET web application. The options were less either to Sql Server Database or File System. Share point option was ruled out because of internal issues. Sharing one of the comparison study we made that time, might be helpful to someone who is looking for the same. 

It requires less work - Storing and retrieving binary data stored within the database involves more code than when working with the data through the file system. It's also easier to update the binary data - no need for talking to the database, just overwrite the file!
Performance - Since the files are stored on the file system rather than on the database, the application is accessing less data from the database, reducing the demand on the database and lessening the network congestion between the web and database server. Database operations are more costly than file system.
Storage Limit: Storing files in the DB is great for small files and if we are sure that the size will not grow out of expectations.  In SQL Server we have limited options when you exceed the physical storage capacity of the box. The bulky database makes may creates problems in backing up the data, moving the data from one database server to another, replicating the database, and so on, is much easier because there's no worry about copying over or backing up the binary content stored in the file system. Taking backup and recovery will be more time consuming with Database storing.
Security: File system storage is great, but keep in mind that you're going to have to keep file permissions or security in mind than you would if you stored them in the DB.
Advantages of storing Binary Data in the Database...
1.    Enforcing referential integrity
2.    Tighter security as you doesn’t have to grant the web user account write access to a folder it is serving content from. Also you get the security of the sql server
3.    All files are backed up when the db is backed up
I would recommend having a shared drive where we can upload files and can store the file path in DB. That will be more simple and best solution. If we are having any issues of getting shared rive, storing in DB is definitely a solution. But we should be able to estimate the volume of the file to be stored.