用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c#代码库

利用WebClient上传文件到web服务器

2014-05-24 作者: 苏起举报

[c#]代码库

/**/
      /// <summary>
      /// WebClient上传文件至服务器
      /// </summary>
      /// <param name="fileNamePath">文件名,全路径格式</param>
      /// <param name="uriString">服务器文件夹路径</param>
      /// <param name="IsAutoRename">是否自动按照时间重命名</param>
      public void UpLoadFile(string fileNamePath, string uriString)
      {
          string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
          string NewFileName = fileName;
 
          string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
          if (uriString.EndsWith("/") == false) uriString = uriString + "/";
 
          uriString = uriString + NewFileName;
          //Utility.LogWriter log = new Utility.LogWriter();
          //log.AddLog(uriString, "Log");
          //log.AddLog(fileNamePath, "Log");
          /**/
          /**/
          /**/
          /// 创建WebClient实例
          WebClient myWebClient = new WebClient();
          myWebClient.Credentials = CredentialCache.DefaultCredentials;
          // 要上传的文件
          FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
          //FileStream fs = OpenFile();
          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();
                  //   log.AddLog("上传日志文件成功!", "Log");
              }
              else
              {
                  postStream.Close();
                  fs.Dispose();
                  //  log.AddLog("上传日志文件失败,文件不可写!", "Log");
              }
 
          }
          catch (Exception err)
          {
              postStream.Close();
              fs.Dispose();
              //Utility.LogWriter log = new Utility.LogWriter();
              // log.AddLog(err, "上传日志文件异常!", "Log");
              throw err;
          }
          finally
          {
              postStream.Close();
              fs.Dispose();
          }
      }


网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...