.net 筆記

學習.net
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

FTP 上傳文件 function

Posted on 2007-10-08 18:02  陳偉  阅读(162)  评论(0)    收藏  举报

 private string Upload(string filename)
        {
            FileInfo fileInf = new FileInfo(filename);

            string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
            URL = uri.Substring(6);
            MessageBox.Show(URL);

            MessageBox.Show(uri);
           
            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));

            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

            reqFTP.KeepAlive = false;

            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            reqFTP.UseBinary = true;

            reqFTP.ContentLength = fileInf.Length;

            int buffLength = 2048;

            byte[] buff = new byte[buffLength];
            int contentLen;

            FileStream fs = fileInf.OpenRead();
            try
            {
                Stream strm = reqFTP.GetRequestStream();

                contentLen = fs.Read(buff, 0, buffLength);

                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);

                    contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();

                //MessageBox.Show("success", "Upload Error");
                return "success";
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Upload Error");
                return ex.Message;
            }
        }