添加引用
using System.IO;
using System.Net;
/// <summary>
/// 上传文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void label3_Click(object sender, EventArgs e)
{
#region 获取上传文件及上传路径
string FileNamePath="";//要上传的文件名称及本地路径
string PropertiesPaeh="";//将文件上传到项目中的位置
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
FileNamePath = ofd.FileName;
}
PropertiesPaeh = System.IO.Path.GetFullPath(
System.IO.Directory.GetCurrentDirectory() + "../../../Template\\"
);//上传路径
#endregion
UpLoadFile(FileNamePath, PropertiesPaeh);
}
/// <summary>
/// 上传方法
/// </summary>
/// <param name="fileNamePath">要上传的文件路径(包括文件名称)</param>
/// <param name="uriString">上传路径</param>
private void UpLoadFile(string fileNamePath, string uriString)
{
//获取上传文件名称
string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
//获取上传文件的类型
string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
uriString = uriString + fileName;
/// 创建WebClient实例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
// 要上传的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
try
{
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
}
else
{
MessageBox.Show("文件目前不可写");
}
postStream.Close();
}
catch
{
MessageBox.Show("文件上传失败,请稍候重试");
}
}