string file = Application.StartupPath + @"\test\test.txt";
string filename = "test";
string url = "http://my.url";
try {
if (!File.Exists(file)){
MessageBox.Show(String.Format("Файл '{0}', не найден!", file),
"Ошибка загрузки файла", MessageBoxButton.OK,
MessageBoxImage.Error);
return;
}
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(url);
string boundary =
"---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes =
System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
req.Method = "POST";
req.ContentType = "multipart/form-data; boundary=" + boundary;
Stream rs = new System.IO.MemoryStream();
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(
String.Format(
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n",
"file", filename
));
rs.Write(boundarybytes, 0, boundarybytes.Length);
rs.Write(headerbytes, 0, headerbytes.Length);
using (var sr = File.Open(file, FileMode.Open))
{
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = sr.Read(buffer, 0, buffer.Length)) != 0)
rs.Write(buffer, 0, bytesRead);
}
byte[] trailer =
System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
req.ContentLength = rs.Length;
using (Stream requestStream = req.GetRequestStream())
{
rs.Position = 0;
byte[] tempBuffer = new byte[rs.Length];
rs.Read(tempBuffer, 0, tempBuffer.Length);
rs.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
}
using (HttpWebResponse res = (HttpWebResponse) req.GetResponse())
{
string respText;
using (Stream responseStream = res.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
respText = reader.ReadToEnd();
MessageBox.Show(respText);//ответ
}
}
catch (Exception exception)
{
MessageBox.Show(
String.Format("Ошибка загрузки файла '{0}'!\n", filename) +
exception.Message, "Ошибка загрузки файла", MessageBoxButton.OK,
MessageBoxImage.Error);
}
if (!Directory.Exists(Application.StartupPath + @"\test"))
MessageBox.Show("Папка test не найдена");
else if (!File.Exists(Application.StartupPath + @"\test\test.txt"))
MessageBox.Show("Файл test.txt не найден");
else
MessageBox.Show("Всё ок");
Assembly.GetExecutingAssembly().Location + @"\test\test.txt"
//или
Application.StartupPath + @"\test\test.txt"