soundy
soundy

Reputation: 307

Upload file using HttpWebRequest -- Couldn't upload?

Here is the code - upload file to uri. I can't upload it. Is anything wrong?

string fileToUpload = @"F:\\upload_file.txt";
FileStream rdr = new FileStream(fileToUpload, FileMode.Open);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:8080/upload.txt"); //Given URI is exists
req.Method = "POST"; 
req.ContentLength = rdr.Length;
req.AllowWriteStreamBuffering = true;
Stream reqStream = req.GetRequestStream();
Console.WriteLine(rdr.Length);                
byte[] inData = new byte[rdr.Length];

// Get data from upload file to inData 
int bytesRead = rdr.Read(inData, 0, (int)rdr.Length);

// put data into request stream
reqStream.Write(inData, 0, (int)rdr.Length);
rdr.Close();

req.GetResponse();
// after uploading close stream 
reqStream.Close(); 

Upvotes: 0

Views: 1941

Answers (1)

MaxSan
MaxSan

Reputation: 318

At first glance I think there may be something wrong with the file your selecting the @ should be used to define a specific string. No escape characters are needed. Vice-versa with the string below in your web request.

So you should correct it either to @"F:\upload_file.txt"; or "F:\\upload_file.txt";

Upvotes: 4

Related Questions