C#文件上传和文件下载

 1 #region 文件上传  

 2    private void UpLoadFile(string fileName, string fileNamePath, string uriString)  

 3    {  

 4        string NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf(".")); string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);  

 5        if (uriString.EndsWith("/") == false)  

 6            uriString = uriString + "/";  

 7        uriString = uriString + NewFileName;  

 8        WebClient myWebClient = new WebClient();  

 9        myWebClient.Credentials = CredentialCache.DefaultCredentials;  

10        FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs);  

11        try  

12        {  

13            byte[] postArray = r.ReadBytes((int)fs.Length); Stream postStream = myWebClient.OpenWrite(uriString, "PUT");  

14            if (postStream.CanWrite) { postStream.Write(postArray, 0, postArray.Length); }  

15            else { MessageBox.Show("文件目前不可写!"); } postStream.Close();  

16        }  

17        catch (Exception ex) { MessageBox.Show(ex.Message); }  

18    }  

19    #endregion  

20  

21  

22    #region C#下载服务器文件至客户端的代码:  

23    public void Download(string URL, string Dir)  

24    {  

25        WebClient client = new WebClient(); string fileName = URL.Substring(URL.LastIndexOf("\\") + 1);  

26        //被下载的文件名   

27        string Path = Dir + fileName;  

28        //另存为的绝对路径+文件名  

29        try { WebRequest myre = WebRequest.Create(URL); }  

30        catch  

31        {  

32            MessageBox.Show(exp.Message, "Error");  

33        }  

34        try { client.DownloadFile(URL, Path); }  

35        catch { MessageBox.Show(exp.Message, "Error"); }  

36    }  

37  

38  

39    #endregion  

 

你可能感兴趣的:(文件上传)