添加引用:
using System.IO;
using System.Net;
//定义一个文件上传函数
private void UpLoadFile(string fileNamePath, string uriString)
{
string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("//") + 1);
string NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + fileName;
//MessageBox.Show("NewfileName=" + NewFileName);
string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
MessageBox.Show("fileNameExt=" + fileNameExt);
uriString = uriString + NewFileName;
//MessageBox.Show("uriString=" + uriString);
/**/
/// 创建WebClient实例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
// 要上传的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
try
{
//使用UploadFile方法可以用下面的格式
//myWebClient.UploadFile(uriString,"PUT",fileNamePath);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
}
else
{
//AppHelper.MessageService.ShowError("文件目前不可写!");
MessageBox.Show("文件目前不可写");
}
postStream.Close();
}
catch
{
// AppHelper.MessageService.ShowError("文件上传失败,请稍候重试~");
MessageBox.Show("文件上传失败,请稍候重试");
}
}
//点击上传实现上传完成,并且上传的文件显示在C盘下
private void button1_Click(object sender, EventArgs e)
{
UpLoadFile(textBox1.Text, "C://");
}
//点击浏览按钮,文件路径显示在文本框中
private void button2_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Word文档(*.doc)|*.doc|文本文档(*.txt)|*.txt|RTF文档(*.rtf)|*.rtf|所有文档(*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string filename = openFileDialog1.FileName;
textBox1.Text = filename;
}
}