473,468 Members | 1,307 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to upload a file in C#.net

5 New Member
hai everybody,

can anyone explain me or give some idea abt uloading of a file.
thanq
vidyu
Sep 1 '06 #1
5 24370
munavvar
3 New Member
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
Sep 1 '06 #2
nickykln
1 New Member
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.  
Oct 12 '06 #3
Wooten26
2 New Member
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
May 10 '07 #4
Wooten26
2 New Member
Nevermind, found good code class here to do it :))
May 10 '07 #5
himanshu1907
1 New Member
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);
}
}
Nov 4 '09 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Muppy | last post by:
I've created a page with a form to upload files: <h1>Upload di un file</h1> <form enctype="multipart/form-data" method="post" action="do_upload1.php"> <p><strong>File da trasferire:</strong><br>...
5
by: Dave Smithz | last post by:
Hi There, I have a PHP script that sends an email with attachment and works great when provided the path to the file to send. However this file needs to be on the same server as the script. ...
1
by: Selena | last post by:
I have vb.net windows application which need to upload file to server. It can run properly without using VPN. How can I run it with VPN? Is there any components or code to upload file? Or is there...
3
by: Brian | last post by:
Hi, I've been trying to find a way to upload file to another site that is not using IIS. The site that I want to upload file to has a simple php script to receive file uploaded through standard...
1
by: akiko | last post by:
i am student and i must to do project about web app by Ruby on rails i can not do past upload file.i try looking code but i just meet upload file image. i want to code upload file that it must to...
4
by: bienwell | last post by:
Hi all, I developed an web page in ASP.NET to upload file into the server. In the Web.config file, I declared <httpRuntime executionTimeout="1200" maxRequestLength="400000" /> The MAX...
4
by: google.com | last post by:
Hi there! I've been digging around looking for a sample on how to upload a file without user action. I found the following article covering the area: ...
6
by: | last post by:
Hi, I use upload control, how to enable upload *.pdf file and enlarge file size? Please help.
1
by: printline | last post by:
Hello all I have a php script that uploads a file from a form into a directory. The directory is automatically created through the script. But the upload file is not put in to the directory,...
2
by: lka527 | last post by:
I am trying to make a site available for someone to *upload* certain type of text file (.txt) that can be parsed by written code. the upload file is available on the main site but I need this to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.