iis6.0 条件:必须启用WEBDAV 需要将要上传到的目录权限加上匿名登陆,而且必须在IIS上创建虚拟目录,将文件上传到虚拟目录才能成功,否则就会出现403禁止错误下面放上我测试好的代码。
/// <summary> /// 上传文件到服务器 /// </summary>
/// <param name="localFile">本地文件 如c;ad.jpg</param>
/// <param name="urlString">上传文件路径 如 http://ab.com/ </param>
/// <param name="isRenName">是否重命名</param>
/// <returns></returns>
public static string UploadFile(string localFile,string urlString,bool isRenName) {
string fileName = localFile.Substring(localFile.LastIndexOf('\')+1);
if (isRenName) {
fileName = DateTime.Now.ToString("yyyyMMddhhsss")+ Path.GetExtension(localFile) ; }
WebClient web = new WebClient();
web.Credentials = CredentialCache.DefaultCredentials;
FileStream fs = new FileStream(localFile,FileMode.Open,FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] by = br.ReadBytes((int)fs.Length);
Stream postStream = web.OpenWrite(urlString+fileName,"PUT");
if (postStream.CanWrite) {
postStream.Write(by, 0, by.Length);
postStream.Flush();
postStream.Close();
fs.Dispose(); }
return urlString;
}