private void btnFileUpload_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
btnFileUpload.Text = openFileDialog1.FileName;
string path= Path.GetFullPath(openFileDialog1.FileName);
int ilength=Directory.GetCurrentDirectory().IndexOf("\\bin");
string savepath = Directory.GetCurrentDirectory().Substring(0, ilength) + "\\Manage";//需要确定上传文件夹,现在默认在Manage文件下
UpLoadFile(path, savepath, false);
}
public void UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)
{
string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
string NewFileName = fileName;
if (IsAutoRename)
{
NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));
}
string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (uriString.EndsWith("/") == false) uriString = uriString + "/";
uriString = uriString + NewFileName;
/// 创建WebClient实例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
try
{
// 要上传的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
try
{
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
postStream.Close();
fs.Dispose();
}
else
{
postStream.Close();
fs.Dispose();
}
}
catch
{
postStream.Close();
fs.Dispose();
}
finally
{
postStream.Close();
fs.Dispose();
}
}
catch
{
MessageBox.Show("上传失败!","系统提示");
}
}
窗体上传文件方式
最新推荐文章于 2021-12-24 17:13:53 发布