Connecting Tech Pros Worldwide Forums | Help | Site Map

How to upload a file in C#.net

Newbie
 
Join Date: Aug 2006
Posts: 5
#1: Sep 1 '06
hai everybody,

can anyone explain me or give some idea abt uloading of a file.
thanq
vidyu

Newbie
 
Join Date: Aug 2006
Posts: 3
#2: Sep 1 '06

re: How to upload a file in C#.net


Hi Vidyu,

Firstly put this below line in the Aspx page.
Expand|Select|Wrap|Line Numbers
  1. <input id="fileUpload" type="file" name="fileUpload" runat="server">
  2.  
write the below following code in the viewcode page
Expand|Select|Wrap|Line Numbers
  1.         private void Button1_Click(object sender, System.EventArgs e)
  2.         {
  3.             string strFileName;
  4.  
  5.             if (File1.PostedFile != null) 
  6.             {      
  7.                 strFileName = File1.PostedFile.FileName;
  8.                 strFileName = strFileName.Substring(strFileName.LastIndexOf("\\")+1);
  9.                 try 
  10.                 {
  11.                     File1.PostedFile.SaveAs("c:\\upload\\"+strFileName);
  12.                     lblMessage.Text = "Uploaded successfully: c:\\upload\\" + strFileName+"<br>";
  13.                 }
  14.                 catch (Exception err) 
  15.                 {
  16.                     lblMessage.Text  = "Error Uploading c:\\upload\\" + strFileName+"<br>";
  17.                 }
  18.             }
  19.         }
  20.  
  21.  
This way you can upload the file to C:\Upload folder. Try out and get back to me if you still have any issues.

Munavvar
Newbie
 
Join Date: Oct 2006
Posts: 1
#3: Oct 12 '06

re: How to upload a file in C#.net


Thanks very much for your help but unfortunatly I didn't manage to make your code work.

Find below another possible implementation that works for me and that is maybe easier.

Hope it helps,

Nico

Expand|Select|Wrap|Line Numbers
  1.  
  2. private void uploadFile(String p_sURL, String p_sFileName, NameValueCollection p_oParameters) 
  3. {
  4.  
  5.     HttpWebRequest oRequest = (HttpWebRequest) WebRequest.Create(p_sURL);
  6.  
  7.     string boundary = Guid.NewGuid().ToString().Replace("-","");
  8.     oRequest.ContentType = "multipart/form-data; boundary=" + boundary;
  9.     oRequest.Method = "POST";
  10.  
  11.     MemoryStream postData = new MemoryStream();
  12.     string newLine = "\r\n";
  13.     StreamWriter sw = new StreamWriter(postData);
  14.  
  15.     // Create a part for each parameter sent in the post request
  16.  
  17.     foreach(string key in p_oParameters.Keys)
  18.     {
  19.         string sValue = p_oParameters[key];
  20.         sw.Write("--" + boundary + newLine);
  21.         sw.Write("Content-Disposition: form-data; name=\"{0}\"; {1}", key, newLine);
  22.         sw.Write(newLine + sValue + newLine);
  23.     }
  24.  
  25.     // Begining Part that contains the file content
  26.  
  27.     sw.Write("--" + boundary + newLine);
  28.     sw.Write("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", "file", p_sFileName, newLine);
  29.     sw.Write("Content-Type: image/pjpeg " + newLine + newLine);
  30.     sw.Flush();
  31.  
  32.     FileStream fileStream = new FileStream(p_sFileName, FileMode.Open, FileAccess.Read); 
  33.     Console.Out.WriteLine("File = " + fileStream.Name + "length=" + fileStream.Length);
  34.  
  35.     byte[] buffer = new byte[1024]; 
  36.     int bytesRead = 0; 
  37.  
  38.     Stream memStream = new System.IO.MemoryStream(); 
  39.  
  40.     while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 ) 
  41.     { 
  42.         memStream.Write(buffer, 0, bytesRead); 
  43.     } 
  44.  
  45.     memStream.Position = 0; 
  46.     byte[] contents = new byte[memStream.Length]; 
  47.     memStream.Read(contents,0,contents.Length); 
  48.     memStream.Close(); 
  49.  
  50.     postData.Write(contents, 0, contents.Length);
  51.     sw.Write(newLine);
  52.     sw.Write("--{0}--{1}", boundary, newLine);
  53.     sw.Flush();
  54.  
  55.     oRequest.ContentLength = postData.Length;
  56.     using (Stream s = oRequest.GetRequestStream())
  57.         postData.WriteTo(s);
  58.     postData.Close();
  59.  
  60. }
  61.  
Newbie
 
Join Date: May 2007
Posts: 2
#4: May 10 '07

re: How to upload a file in C#.net


Could this be modified to send data to a webform from a c# application? Or could I get a link to some source that will do that? (Not thru URL, but to the webforms on submit URL as if the form was filled in -- looking for a way to send larger amounts of data to a webpage than url encoding will allow, yet not large enough to require a file upload)

Thank You (and ya.. I know this is an old post.. found it googling)

-Norman
Newbie
 
Join Date: May 2007
Posts: 2
#5: May 10 '07

re: How to upload a file in C#.net


Nevermind, found good code class here to do it :))
Newbie
 
Join Date: Nov 2009
Posts: 1
#6: 3 Weeks Ago

re: How to upload a file in C#.net


In aspx Page:

<tr>
<td align="center">
<asp:FileUpload ID="fileUploadBrowse" runat="server" CssClass="fileUpload" />
</td>
</tr>
<tr>
<td align="center">
<asp:Button ID="uploadButton" runat="server" CssClass="button" OnClick="UploadButton_Click"
Text="Upload" />
</td>
</tr>

In aspx.cs Page
private string Path = ConfigurationManager.AppSettings["DocumentUploadedFilePath"];
public Stream UploadedFile
{
get
{
HttpPostedFile file = fileUploadBrowse.PostedFile;
return file.InputStream;
}
}
public string ClientFilePath
{
get
{
return fileUploadBrowse.PostedFile.FileName.ToString();
}
}

public string FileName
{
get
{
HttpPostedFile file = fileUploadBrowse.PostedFile;
return System.IO.Path.GetFileName(this.ClientFilePath);
}
}

protected void UploadButton_Click(object sender, EventArgs e)
{
UploadFileToServer(this.FileName, this.UploadedFile);
}

public void UploadFileToServer(string fileName, Stream uploadedFile)
{
byte[] buffer = new byte[65000];
int bytesRead = 0;
try
{
while ((bytesRead = uploadedFile.Read(buffer, 0, 65000)) > 0)
{
this.AppendFileToServer(fileName, buffer, 0, bytesRead);
}
}
catch (Exception ex)
{
throw (ex);
}

}
private void AppendFileToServer(string fileName, byte[] data, int offset, int count)
{
try
{
string fileUploadedPath = this.Path + "\\" + fileName;
using (FileStream fileStream = new FileStream(fileUploadedPath, FileMode.Append, FileAccess.Write))
{
fileStream.Write(data, offset, count);
fileStream.Close();
}
}
catch (Exception ex)
{
throw (ex);
}
}
Reply