// Command line arguments are two strings: // 1. The url that is the name of the file being uploaded to the server. // 2. The name of the file on the local machine. // public FtpState Upload(string _file, string _uri, string _account, string _pass, UploadStepDelegate _stepDelegate) { state = new FtpState(); request = (FtpWebRequest)WebRequest.Create(new Uri(_uri + "/" + Path.GetFileName(_file))); request.Method = WebRequestMethods.Ftp.UploadFile; // This example uses anonymous logon. // The request is anonymous by default; the credential does not have to be specified. // The example specifies the credential only to // control how actions are logged on the server. request.Credentials = new NetworkCredential(_account, _pass); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.FileName = _file; state.StepProgressDelegate = _stepDelegate; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); return(state); }
public static string FtpFileUpload(string ftpUri, string ftpUsername, string ftpPassword, string fileFullPath, string fileName) { ManualResetEvent waitObject; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri + fileName); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(ftpUsername, ftpPassword); state.Request = request; state.FileName = fileFullPath; waitObject = state.OperationComplete; request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { return(state.OperationException.Message); } else { return(string.Empty); } }
public void UpLoad(string url, string uname, string pwd, string ppath) { ManualResetEvent waitObject; FileInfo fileInf = new FileInfo(ppath); string fileName = fileInf.Name; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + url + "/" + fileInf.Name)); request.Method = WebRequestMethods.Ftp.UploadFile; request.KeepAlive = false; request.Credentials = new NetworkCredential(uname, pwd); state.Request = request; state.FileName = ppath; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream(new AsyncCallback(EndGetStreamCallback), state); // Block the current thread until all operations are complete. // waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { B_Site_Log.Insert("FTP1", state.OperationException.ToString()); throw state.OperationException; } else { } }
public static void UploadFileAsync(string uriString, string fileName, string userName, string password) { ManualResetEvent waitObject; Uri uri = new Uri(uriString); FtpState ftpState = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.File.UploadFile; request.Credentials = new NetworkCredential(userName, password); ftpState.Request = request; ftpState.FileName = fileName; waitObject = ftpState.OperationComplete; request.BeginGetRequestStream(new AsyncCallback(EndGetStreamCallback), ftpState); // Block the current thread until all operations are complete. waitObject.WaitOne(); if (ftpState.OperationException != null) { throw ftpState.OperationException; } else { Console.WriteLine("The operation completed - {0}", ftpState.StatusDescription); } }
public bool Main(string url, string caminho, string user, string palavra, ref string msg, bool modo) { msg = ""; // Create a Uri instance with the specified URI string. // If the URI is not correctly formed, the Uri constructor // will throw an exception. ManualResetEvent waitObject; Uri target = new Uri(url); string fileName = caminho; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); request.Method = WebRequestMethods.Ftp.UploadFile; // This example uses anonymous logon. // The request is anonymous by default; the credential does not have to be specified. // The example specifies the credential only to // control how actions are logged on the server. request.Credentials = new NetworkCredential(user, palavra); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.FileName = fileName; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { msg = state.OperationException.ToString(); return(false);//throw ex; } else { if (File.Exists(state.FileName)) { if (modo == true) { File.Delete(state.FileName); } } msg = "The operation completed - " + state.StatusDescription; return(true);//throw ex; } }
private void UploadNextFile(IAsyncResult ar) { //清空 _currLength = 0; _abort = false; if (_uploadResponse != null) { _uploadResponse.Close(); } if (_fileStream != null) { _fileStream.Close(); } if (_requestStream != null) { _requestStream.Close(); } _uploadResponse = (FtpWebResponse)_uploadRequest.EndGetResponse(ar); //_result = "文件上传成功"; try { if (_uploadFiles.Count != 0) { FileInfo file = _uploadFiles[0] as FileInfo; ServerFileInfo serverFile = SearchFile(file.Name.Replace('#', '_')); if (serverFile != null) { _currLength = serverFile.Size; } else { _currLength = 0; } string uploadUrl = @"ftp://" + this.Address + ":" + this.Port + "/" + file.Name.Replace('#', '_'); _uploadRequest = (FtpWebRequest)WebRequest.Create(uploadUrl); if ((bool)_uploadFilesStateTable[file]) {//覆盖 _uploadRequest.Method = WebRequestMethods.Ftp.UploadFile; _currLength = 0; } else { _uploadRequest.Method = _currLength == 0 ? WebRequestMethods.Ftp.UploadFile : WebRequestMethods.Ftp.AppendFile; } _uploadRequest.Credentials = new NetworkCredential(this.UserName, this.Password); _uploadRequest.Proxy = null; _uploadRequest.KeepAlive = false; _uploadRequest.BeginGetRequestStream(new AsyncCallback(TransFile), file); } } catch (Exception e) { _result = e.Message; } }
/// <summary> /// Uploads a file from to the FTP server /// </summary> /// <param name="localFilePath">The path of the file to upload</param> /// <param name="remoteFileName">The name of the file on remote server</param> public virtual void PutFile(string localFilePath, string remoteFileName) { if (string.IsNullOrEmpty(this.RemoteHost)) { throw new IOException("Remote host is undefined."); } ManualResetEvent waitObject; FtpState state = new FtpState(); string remoteFileUri; string remoteHost = _RemoteHost.Trim(); if (!remoteHost.StartsWith("ftp://")) { remoteHost = "ftp://" + remoteHost; } if (remoteHost.EndsWith("/")) { remoteFileUri = remoteHost + remoteFileName; } else { remoteFileUri = remoteHost + "/" + remoteFileName; } Uri target = new Uri(remoteFileUri); FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(target); ftpReq.UseBinary = this.TransferType == FtpTransferType.BINARY; ftpReq.Credentials = new NetworkCredential(this.UserName, this.Password); ftpReq.Method = WebRequestMethods.Ftp.UploadFile; // Store the request in the object that we pass into the // asynchronous operations. state.Request = ftpReq; state.FileName = localFilePath; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. ftpReq.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } }
public static void SendFile(string FTPSite, string fileName, string user, string pass, string fullPath) { // Create a Uri instance with the specified URI string. // If the URI is not correctly formed, the Uri constructor // will throw an exception. ManualResetEvent waitObject; Uri target = new Uri(FTPSite); FtpState state = new FtpState(); //FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target + @"/" + fileName); //FtpWebRequest request = (FtpWebRequest)WebRequest.Create(@"ftp://10.1.36.34/"); request.Method = WebRequestMethods.Ftp.UploadFile; // This example uses anonymous logon. // The request is anonymous by default; the credential does not have to be specified. // The example specifies the credential only to // control how actions are logged on the server. request.Proxy = null; request.Credentials = new NetworkCredential(user, pass); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; // Set a time limit for the operation to complete. request.Timeout = 600000; //state.FileName = @"C:\Software\PFCApps\IntranetSite\PurchaseImport\XML\PFC_Order_11050303_toms.xml"; ; state.FileName = fullPath; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } else { //lblSuccessMessage.Text = "XML sent to " + FTPSite; //MessageUpdatePanel.Update(); } }
// Command line arguments are two strings: // 1. The url that is the name of the file being uploaded to the server. // 2. The name of the file on the local machine. // public void Upload(string ftpUri, string filename, string username, string password) { Uri = ftpUri; Filename = filename; UserName = username; Password = password; // Create a Uri instance with the specified URI string. // If the URI is not correctly formed, the Uri constructor // will throw an exception. ManualResetEvent waitObject; Uri target = new Uri(this.Uri); string fileName = this.Filename; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); request.Method = WebRequestMethods.Ftp.UploadFile; request.EnableSsl = true; string file = Path.Combine(Application.StartupPath, "Passive.txt"); if (File.Exists(file)) { string content = File.ReadAllText(file); bool passive; if (Boolean.TryParse(content, out passive)) { request.UsePassive = passive; } } // This example uses anonymous logon. // The request is anonymous by default; the credential does not have to be specified. // The example specifies the credential only to // control how actions are logged on the server. request.Credentials = new NetworkCredential(this.UserName, this.Password); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.FileName = fileName; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); }
public static void UploadFileToServer(string targetURI, string filename) { //TODO: Check that the file doesn't already exist before uploading // See: http://stackoverflow.com/questions/347897/how-to-check-if-file-exists-on-ftp-before-ftpwebrequest // Create a Uri instance with the specified URI string. // If the URI is not correctly formed, the Uri constructor // will throw an exception. ManualResetEvent waitObject; Uri target = new Uri(targetURI); string fileName = filename; FTPState state = new FTPState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); request.Method = WebRequestMethods.Ftp.UploadFile; // Enable SSL request.EnableSsl = true; // Set credentials request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["FTPAccount"], ConfigurationManager.AppSettings["FTPPassword"]); request.KeepAlive = false; // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.FileName = fileName; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } else { Console.WriteLine("The operation completed - {0}", state.StatusDescription); } }
public void UpLoad(object obj) { object[] objs = (object[])obj; List <string> uploadfilePath = objs[3] as List <string>; for (int i = 0; i < uploadfilePath.Count(); i++) { try { FtpState state = new FtpState(); state.FilePath = uploadfilePath[i]; ManualResetEvent waitObject; FileInfo fileInf = new FileInfo(state.FilePath); string fileName = fileInf.Name; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + objs[0] + "/zdsoft/bill_upload/" + fileInf.Name)); request.Method = WebRequestMethods.Ftp.UploadFile; request.Timeout = 60 * 60 * 1000; request.KeepAlive = false; request.Credentials = new NetworkCredential(objs[1].ToString(), objs[2].ToString()); request.Proxy = null; request.KeepAlive = false; request.ContentLength = fileInf.Length; state.Request = request; state.FileName = state.FilePath; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. IAsyncResult ir = request.BeginGetRequestStream(new AsyncCallback(EndGetStreamCallback), state); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } else { Console.WriteLine("The operation completed - {0}", state.StatusDescription); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
// Command line arguments are two strings: // 1. The url that is the name of the file being uploaded to the server. // 2. The name of the file on the local machine. // public void UploadFile(string[] args) { // Create a Uri instance with the specified URI string. // If the URI is not correctly formed, the Uri constructor // will throw an exception. ManualResetEvent waitObject; Uri target = new Uri(args[0]); string fileName = args[1]; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); request.Method = WebRequestMethods.Ftp.UploadFile; request.UseBinary = true; request.KeepAlive = false; request.UsePassive = false; // This example uses anonymous logon. // The request is anonymous by default; the credential does not have to be specified. // The example specifies the credential only to // control how actions are logged on the server. request.Credentials = new NetworkCredential("lujyftp", "eman201788"); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.FileName = fileName; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } else { Console.WriteLine("The operation completed - {0}", state.StatusDescription); } }
// Command line arguments are two strings: // 1. The url that is the name of the file being uploaded to the server. // 2. The name of the file on the local machine. // public void UpLoader(List <FilePathInfo> filelist) { foreach (FilePathInfo eFilePathInfo in filelist) { // Create a Uri instance with the specified URI string. // If the URI is not correctly formed, the Uri constructor // will throw an exception. ManualResetEvent waitObject; Uri target = new Uri(string.Format("ftp://{0}:{1}/", m_strIP, m_nPort) + eFilePathInfo.FileNameWithSuf); string fileName = eFilePathInfo.FilePath; CheckFileExist(eFilePathInfo.FileFolder.Substring(eFilePathInfo.nKillPathLen) + "\\"); FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); request.Credentials = new NetworkCredential(m_strName, m_strPassword); request.Method = WebRequestMethods.Ftp.UploadFile; // This example uses anonymous logon. // The request is anonymous by default; the credential does not have to be specified. // The example specifies the credential only to // control how actions are logged on the server. // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.FileName = fileName; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } else { //MessageBox.Show("The operation completed : " + state.StatusDescription, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
public static bool PutFile(string fileName, string destinationServer, string userName, string password) { // Create a Uri instance with the specified URI string. // If the URI is not correctly formed, the Uri constructor // will throw an exception. ManualResetEvent waitObject; bool bOut = false; Uri target = new Uri(destinationServer); FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); request.Method = WebRequestMethods.Ftp.UploadFile; // The request is anonymous by default; the credential does not have to be specified. // The example specifies the credential only to // control how actions are logged on the server. request.Credentials = new NetworkCredential(userName, password); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.FileName = fileName; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } else { //log this ("The operation completed - {0}", state.StatusDescription); bOut = true; } return(bOut); }
public bool UploadFile(IList files) { try { //区分第一次 if (files != null) { _uploadFiles = files; } _abort = false; if (_uploadFiles.Count != 0) { FileInfo file = _uploadFiles[0] as FileInfo; //把'#'替换为'_' ServerFileInfo serverFile = SearchFile(file.Name.Replace('#', '_')); if (serverFile != null) { _currLength = serverFile.Size; } else { _currLength = 0; } string uploadUrl = FTP_URL_PREFIX + file.Name.Replace('#', '_'); _uploadRequest = (FtpWebRequest)WebRequest.Create(uploadUrl); if ((bool)_uploadFilesStateTable[file]) {//覆盖 _uploadRequest.Method = WebRequestMethods.Ftp.UploadFile; _currLength = 0; } else { _uploadRequest.Method = _currLength == 0 ? WebRequestMethods.Ftp.UploadFile : WebRequestMethods.Ftp.AppendFile; } _uploadRequest.Credentials = new NetworkCredential(this.UserName, this.Password); _uploadRequest.Proxy = null; _uploadRequest.KeepAlive = false; _uploadRequest.BeginGetRequestStream(new AsyncCallback(TransFile), file); } return(true); } catch (Exception e) { _result = e.Message; return(false); } }
// アップロード(非同期) public static void UploadAsync(string requestUri, string filePath) { FtpWebRequest request = null; try { // 状態管理クラスをオブジェクト化 FtpState state = new FtpState(); // FTPのリクエスト用オブジェクト作成 request = CreateFtpWebRequest(WebRequestMethods.Ftp.UploadFile, requestUri); // 非同期通信管理オブジェクト設定 state.Request = request; state.FilePath = filePath; // 待機オブジェクト ManualResetEvent waitObject = state.OperationComplete; // 非同期リクエスト開始 request.BeginGetRequestStream(new AsyncCallback(EndGetStreamCallback), state); // 処理完了まで待機 waitObject.WaitOne(); // 処理完了 if (state.OperationException != null) { // 例外発生 throw state.OperationException; } else { Console.WriteLine("アップロード処理が正常に終了しました - {0}", state.StatusDescription); } } catch (WebException ex) { Console.WriteLine("【ERROR】アップロード処理 - {0}", ex.Message); throw; } finally { request = null; } }
///////////////////////////////////////////////////////////////////////////////////////////////////// //upload_async_read ///////////////////////////////////////////////////////////////////////////////////////////////////// private bool upload_async_read(string full_filename, string filename, bool alive, string connection_name, int connection_limit) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + address + "/" + directory + "/" + filename); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(username, password); request.KeepAlive = alive; if (!String.IsNullOrEmpty(connection_name)) { request.ConnectionGroupName = connection_name; } request.ServicePoint.ConnectionLimit = connection_limit; FtpState state = new FtpState(request, full_filename); ManualResetEvent wait = state.wait; request.BeginGetRequestStream(new AsyncCallback(get_stream), state); wait.WaitOne(); return(true); }
public CommonResultModel NewFileUpload(string fname) { ManualResetEvent waitObject; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_url + @"/" + fname); request.UseBinary = true; request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(_username, _password); string status = string.Empty; //byte[] b = File.ReadAllBytes(_filePath); state.Request = request; state.FileName = fname; waitObject = state.OperationComplete; request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); waitObject.WaitOne(new TimeSpan(0, 40, 0)); if (state.OperationException != null) { throw state.OperationException; } else { //Console.WriteLine("The operation completed - {0}", state.StatusDescription); } return(new CommonResultModel { IsOK = true, Message = string.Format("Upload File Complete, status {0}", status), }); }
private static void UploadToFTP(string completePath, string _rutaArriba) { if (GlobalParams == null) { return; } ManualResetEvent waitObject; FtpState state = new(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_rutaArriba); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(GlobalParams["ftpUser"], GlobalParams["ftpPassword"]); state.Request = request; state.FileName = completePath; waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } else { //Console.WriteLine("The operation completed - {0}", state.StatusDescription); } CounterFilesUploaded++; }
public static void UploadFile(string fileName) { // Create a Uri instance with the specified URI string. // If the URI is not correctly formed, the Uri constructor // will throw an exception. ManualResetEvent waitObject; FTPSettings ftpSettings = new FTPSettings(); string uriPath = ftpSettings.Path.Trim('/') + "/" + Path.GetFileName(fileName); FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new UriBuilder("ftp", ftpSettings.Host, ftpSettings.Port, uriPath).Uri); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(ftpSettings.UserName, ftpSettings.Password); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.FileName = fileName; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream(new AsyncCallback(EndGetStreamCallback), state); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } }
//上传文件(1、读取文件,将文件转换成流写入到请求流当中。2、发送请求,获得FTP服务器的返回信息) public bool UploadFileToFTP(out string msg, HttpContext context = null) { msg = ""; bool result = false; try { if (GetBuffer(out msg, context)) { string name = saveFileResource(out msg); ;//写到程序所指定的文件夹当中 DbConnection conn = CyDbConnManager.GetActiveDbConnection("CRMDB"); CyQuery query = new CyQuery(conn); DateTime serverTime = CyDbSystem.GetDbServerTime(query); query.SQL.Text = "select IP_NET,PSWD,IP_PUB,DIR from FTPCONFIG WHERE ID=1"; query.Open(); while (!query.Eof) { wxserverurl = query.FieldByName("IP_PUB").AsString; this.ftppwd = query.FieldByName("PSWD").AsString; string FTPDIR = query.FieldByName("DIR").AsString; int t = FTPDIR.LastIndexOf("@"); this.ftpuser = FTPDIR.Substring(0, t); this.ftpurl = "ftp://" + FTPDIR.Substring(t + 1, FTPDIR.Length - t - 1); //this.ftpuser = //obj.sDIR = query.FieldByName("DIR").AsString; //obj.sIP_NET = query.FieldByName("IP_NET").AsString; query.Next(); } query.Close(); //wxserverurl = ConfigurationManager.AppSettings["WXServerIP"].ToString(); //this.ftpurl = ConfigurationManager.AppSettings["WXServerFTP"].ToString(); //this.ftpuser = ConfigurationManager.AppSettings["ftpuser"].ToString(); //this.ftppwd = ConfigurationManager.AppSettings["ftppwd"].ToString(); string year = serverTime.Year.ToString(); string month = (serverTime.Month.ToString().CompareTo("10") > 0) ? serverTime.Month.ToString() : 0 + serverTime.Month.ToString(); string day = (serverTime.Day.ToString().CompareTo("10") > 0) ? serverTime.Day.ToString() : 0 + serverTime.Day.ToString(); dirname = "WXFtp//" + year + month + day; FtpMakeDir("WXFtp"); FtpMakeDir(dirname); Url = ftpurl + "//" + dirname + "//" + filename.Substring(filename.LastIndexOf("/") + 1); Uri uri = new Uri(Url); FtpWebRequest ftprequest = (FtpWebRequest)FtpWebRequest.Create(uri); ftprequest.Method = WebRequestMethods.Ftp.UploadFile;//设置操作类型 //STOR <filename>储存(复制)文件到服务器上 //STOU <filename>储存文件到服务器名称上 ftprequest.Credentials = new NetworkCredential(ftpuser, ftppwd);//设置验证 //与FTP交互有关的类 FtpState state = new FtpState(); if (name == "")//属于只传了个文件绝对路径过来 { state.FileName = this.dir + this.filename; } else//传的是文件流,并且已经保存到了本地 { state.FileName = fullFileName; } //state.FileName = fullFileName; state.Request = ftprequest; // Asynchronously get the stream for the file contents. //将要上传的内容写到请求流当中 ftprequest.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback),//委托 ,相当于事件处理函数 state); waitObject = state.OperationComplete;//用于线程控制 // Block the current thread until all operations are complete. waitObject.WaitOne();//直接收到信号,才开始进程 // The operations either completed or threw an exception. if (state.OperationException != null) { msg = state.OperationException.Message; result = false; } result = true; } else if (msg != "") { msg = "上传到服务器失败"; result = false; } else if (msg == "") { result = true; } } catch (Exception e) { msg = e.Message; result = false; } return(result); }
private static MemoryStream DoOldStyleAsync(FtpWebRequest request, MemoryStream requestBody) { if (requestBody != null) { IAsyncResult ar = request.BeginGetRequestStream(null, null); ar.AsyncWaitHandle.WaitOne(); Stream requestStream = request.EndGetRequestStream(ar); requestBody.CopyTo(requestStream); requestStream.Close(); } IAsyncResult ar2 = request.BeginGetResponse(null, null); ar2.AsyncWaitHandle.WaitOne(); FtpWebResponse response = (FtpWebResponse)request.EndGetResponse(ar2); MemoryStream responseBody = new MemoryStream(); response.GetResponseStream().CopyTo(responseBody); response.Close(); return responseBody; }
private static void HandleFileTransfer(Uri serverUri, string filepath, bool up, string userName, string password, bool enableSSL) { if (serverUri.Scheme != Uri.UriSchemeFtp) { throw new ArgumentException(String.Format("{0} scheme is not ftp", serverUri.AbsoluteUri)); } ManualResetEvent waitObject; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri); request.EnableSsl = enableSSL; if (up) { request.Method = WebRequestMethods.Ftp.UploadFile; } else { request.Method = WebRequestMethods.Ftp.DownloadFile; } request.Credentials = new NetworkCredential(userName, password); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.Argument = filepath; // Get the event to wait on. waitObject = state.OperationComplete; if (up) { // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback(EndGetStreamCallback), state ); } else { request.BeginGetResponse( new AsyncCallback(EndGetResponseCallback), state ); } // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } else { Utils.configLog("I", String.Format("The operation completed - {0}", state.StatusDescription)); } }