我要在windows模式下上传文件,找了好久才找到,现在把他写下来,帮助后来者
方法一
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
WebClient webClient = new WebClient();
webClient.Credentials = CredentialCache.DefaultCredentials;
try
{
//方法一
FileStream fs = new FileStream(@"d:/filetxt.txt", FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = webClient.OpenWrite(@"http://10.227.34.174/upload/filetxt.txt", "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
Console.WriteLine("Success!");
}
else
{
Console.WriteLine("Fail!");
}
postStream.Close();
////方法二
//webClient.UploadFile(@"http://10.227.34.174/upload/filetxt.txt", "PUT", @"d:/filetxt.txt");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
方法二
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
WebClient webClient = new WebClient();
webClient.Credentials = CredentialCache.DefaultCredentials;
try
{
//方法二
webClient.UploadFile(@"http://10.227.34.174/upload/filetxt.txt", "PUT", @"d:/filetxt.txt");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
本文介绍了两种在Windows环境下使用C#进行文件上传的方法。一种是通过读取文件为字节数组并直接写入目标URL;另一种是利用WebClient的UploadFile方法实现。
1223

被折叠的 条评论
为什么被折叠?



