C# WebClient UploadFile测试通过
首先需创建IIS虚拟目录(Upload)并给虚拟目录及实目录均增加匿名访问权限,否则会报403错误
//服务器路径
string Uri = "http://127.0.0.1/Upload/";
//文件路径
string fileName = "mysales.txt";
// 得到文件名,文件扩展名字,服务器路径
Uri = Uri + fileName;
// 创建WebClient实例
WebClient myWebClient = new WebClient();
//访问权限设置
myWebClient.Credentials = CredentialCache.DefaultCredentials;
// 要上传的文件
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
try
{
byte[] postArray = br.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(Uri, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
label1.Text = fileName + "上传成功!";
}
else
{
label1.Text = "文件目前不可写!";
}
postStream.Close();
}
catch (WebException errMsg)
{
label1.Text = "上传失败:" + errMsg.Message;
}