///
/// WebClient上传文件至服务器
///
/// 文件名,全路径格式
/// 服务器文件夹路径
/// 是否自动按照时间重命名
public string shangchuang(string fileNamePath, string uriString, bool IsAutoRename)
{
string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);//截图文件名称
string NewFileName = fileName;
//按时间重命名
if (IsAutoRename == true)
{
NewFileName = DateTime.Now.ToString("yyMMddhhmmss");
NewFileName += DateTime.Now.Millisecond.ToString();
if (fileNamePath.Equals(""))
{
NewFileName += "123";
}
else
{
NewFileName += 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;
// 要上传的文件
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
{
//使用UploadFile方法可以用下面的格式
//myWebClient.UploadFile(uriString,"PUT",fileNamePath);
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
postStream.Close();
fs.Dispose();
}
else
{
postStream.Close();
fs.Dispose();
}
}
catch (Exception err)
{
postStream.Close();
fs.Dispose();
throw err;
}
finally
{
postStream.Close();
fs.Dispose();
fs.Close();
}
return NewFileName;}
}
如果是本地上传的话就更简单了,file方法的复制就可以了。