public void FlUpload(List <decimal> lTeorici) { bool invia_file = false; string pathtemp_idfile = System.Web.HttpContext.Current.Server.MapPath("~"); string strLocalFile = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["FTPCedolinoNomeFileLocal"]); string strLocalFilePath = @pathtemp_idfile + strLocalFile; #region apre il file StreamWriter outputFile = new StreamWriter(Path.Combine(pathtemp_idfile, strLocalFile)); #endregion try { if (lTeorici?.Any() ?? false) { foreach (var teorici in lTeorici) { using (ModelDBISE db = new ModelDBISE()) { var teorici_row = db.TEORICI.Find(teorici); //if (teorici_row.TRASFERIMENTO.DIPENDENTI.MATRICOLA == 2871) //{ //} //verifica che la riga è relativa a PAGHE if ( teorici_row.ANNULLATO == false && teorici_row.DIRETTO == false && teorici_row.ELABORATO == true && teorici_row.VOCI.IDTIPOLIQUIDAZIONE == (decimal)EnumTipoLiquidazione.Paghe ) { #region imposta stringhe fisse var Scheda = "42"; var CodAzienda = "0001"; var CodMatr = String.Format("{0:000000}", teorici_row.TRASFERIMENTO.DIPENDENTI.MATRICOLA); var Filler1 = new String(' ', 2); //Filler1 = " "; var Filler2 = new String('0', 20); //Filler2 = "00000000000000000000"; var Filler3 = new String('0', 12) + new String(' ', 4); //Filler3 = "000000000000 "; var CodCosto = new String('0', 10); // CodCosto = "0000000000"; var CodGruppo = "0"; #endregion decimal idLivello = 0; bool livellotrovato = false; #region verifica se il record è relativo a PRIMA SISTEMAZIONE if (teorici_row?.IDINDSISTLORDA > 0) { idLivello = teorici_row.ELABINDSISTEMAZIONE.IDLIVELLO; livellotrovato = true; } #endregion #region verifica se il record è relativo a RICHIAMO if (teorici_row?.IDELABINDRICHIAMO > 0) { idLivello = teorici_row.ELABINDRICHIAMO.IDLIVELLO; livellotrovato = true; } #endregion #region verifica se il record è relativo a TRASPORTO EFFETTI if (teorici_row?.IDELABTRASPEFFETTI > 0) { idLivello = teorici_row.ELABTRASPEFFETTI.IDLIVELLO; livellotrovato = true; } #endregion #region verifica se il record è relativo a VOCI MANUALI if (teorici_row?.IDAUTOVOCIMANUALI > 0) { livellotrovato = true; var meserif = teorici_row.MESERIFERIMENTO; var annorif = teorici_row.ANNORIFERIMENTO; DateTime primogiornorif = Convert.ToDateTime("01/" + meserif + "/" + annorif); DateTime ultimogiornorif = Utility.GetDtFineMese(primogiornorif); idLivello = teorici_row.AUTOMATISMOVOCIMANUALI .TRASFERIMENTO .DIPENDENTI .LIVELLIDIPENDENTI .Where(a => a.ANNULLATO == false && a.DATAINIZIOVALIDITA <= ultimogiornorif && a.DATAFINEVALIDITA >= ultimogiornorif) .ToList() .First() .IDLIVELLO; } #endregion #region se il livello non viene trovato va in errore if (livellotrovato == false) { throw new Exception(string.Format("Livello non trovato nella corrispondenza sulla tabella TEORICI (idteorici={0})", teorici)); } #endregion var l_livDirigente = db.LIVELLI.Where(a => a.LIVELLO == "D").OrderByDescending(a => a.IDLIVELLO).ToList(); #region se non esiste il livello DIRIGENTE va in errore if (!(l_livDirigente?.Any() ?? false)) { throw new Exception("Non esiste il livello DIRIGENTE (D) nella tabella LIVELLI"); } #endregion #region imposta codice gruppo if (idLivello == l_livDirigente.First().IDLIVELLO) // Dirigente { CodGruppo = "0002"; } else { CodGruppo = "0001"; } #endregion #region imposta importo var Importo = Math.Abs(Math.Round(teorici_row.IMPORTO, 2)); string impNumDueDecimali = Importo.ToString("N2"); string importosenzavirgola = impNumDueDecimali.Replace(",", ""); string importoPadded = importosenzavirgola.PadLeft(9, '0'); var Valore = importoPadded; //var Valore = Importo.ToString().PadLeft(10, '0').Replace(",", ""); #endregion //if (Importo == 0) //{ // var val = 0; // var val1 = val.ToString().PadLeft(10, '0').Replace(",", ""); //} var CodFormula = teorici_row.VOCI.CODICEVOCE; string NrDato = CodFormula; #region imposta NrDato if (teorici_row.IMPORTO < 0) { NrDato = "5" + NrDato.Substring(0, 3); } else { NrDato = "0" + NrDato.Substring(0, 3); } #endregion var codformula = CodFormula.Substring(4, 3); #region scrive solo importi diversi da zero if (Importo != 0) { invia_file = true; outputFile.Write(Scheda + CodAzienda + CodGruppo + CodMatr + Filler1 + NrDato + Filler2 + Valore + CodCosto + codformula + Filler3); } #endregion } } } } #region chiude il file outputFile.Close(); #endregion #region se necessario invia il file if (invia_file) { string strFTPFilePath = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["FTPCedolinoPath"]); string strUserName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["FTPCedolinoUser"]); string strPassword = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["FTPCedolinoPassword"]); //Create a FTP Request Object and Specfiy a Complete Path FtpWebRequest reqObj = (FtpWebRequest)WebRequest.Create(strFTPFilePath); //Call A FileUpload Method of FTP Request Object reqObj.Method = WebRequestMethods.Ftp.UploadFile; //If you want to access Resourse Protected,give UserName and PWD reqObj.Credentials = new NetworkCredential(strUserName, strPassword); // Copy the contents of the file to the byte array. byte[] fileContents = File.ReadAllBytes(strLocalFilePath); reqObj.ContentLength = fileContents.Length; //Upload File to FTPServer Stream requestStream = reqObj.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); FtpWebResponse response = (FtpWebResponse)reqObj.GetResponse(); } #endregion } catch (Exception ex) { #region chiude il file in caso di errore outputFile.Close(); #endregion throw ex; } }
public static string UploadPatch(string local_file, string target) { string error_pre = "FTP Upload local_file=" + local_file + " error:"; string error = ""; string local_md5 = ""; try { local_md5 = MD5Code.GetMD5HashFromFile(local_file); if (string.IsNullOrEmpty(local_md5)) { return("local md5 error"); } var ins = File.ReadAllLines("ftp_config.txt"); string SERVER = ins[0]; string NAME = ins[1]; string PWD = ins[2]; FileInfo f = new FileInfo(local_file); var uri = new Uri(SERVER + "/" + target); FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(uri); reqFtp.UseBinary = true; reqFtp.Credentials = new NetworkCredential(NAME, PWD); reqFtp.KeepAlive = false; // reqFtp.EnableSsl = true; reqFtp.Method = WebRequestMethods.Ftp.UploadFile; reqFtp.ContentLength = f.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; FileStream fs = f.OpenRead(); 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(); //反向下载 并且检查 文件MD5是否正确 // Get the object used to communicate with the server. WebClient request = new WebClient(); // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential(NAME, PWD); try { byte[] newFileData = request.DownloadData(uri.ToString()); string fileString = System.Text.Encoding.UTF8.GetString(newFileData); string tmp_file_name = "tmp_ftp_md5_file.zip"; EditorUtils.Utils.TryDeleteFile(tmp_file_name); var x = File.Create(tmp_file_name); x.Write(newFileData, 0, newFileData.Length); x.Flush(); x.Close(); string remote_md5 = MD5Code.GetMD5HashFromFile(tmp_file_name); if (remote_md5 != local_md5) { return(error_pre + "remote md5 error re-try-upload-operation local=" + local_md5 + " remote=" + remote_md5); } } catch (WebException e) { return(error_pre + e.ToString()); } error = "ok"; } catch (Exception e) { error = error_pre + " error " + e.Message; } return(error); }
public string GerarJSON_TodoJogos(string sChave, string sCampeonato, string sURL) { string json = "[]"; if (sCampeonato.Equals("BR_A")) { if (sURL.ToUpper().Equals("UOL")) { json = TodosJogos.BuscarTodosJogos_Uol("https://esporte.uol.com.br/futebol/campeonatos/brasileirao/jogos/", sCampeonato); } else { json = TodosJogos.BuscarTodosJogos_TabelaBR("http://www.tabeladobrasileirao.net/serie-a/", sCampeonato); } } else if (sCampeonato.Equals("BR_B")) { if (sURL.ToUpper().Equals("UOL")) { json = TodosJogos.BuscarTodosJogos_Uol("https://esporte.uol.com.br/futebol/campeonatos/serie-b/jogos/", sCampeonato); } else { json = TodosJogos.BuscarTodosJogos_TabelaBR("http://www.tabeladobrasileirao.net/serie-b/", sCampeonato); } } if (!json.Equals("[]")) { string sFile = "json_todosjogos_" + sCampeonato + ".json"; // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.inaltum.futebol.servicos.ws/WEB/" + sFile); request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("inaltum", "androidapk1"); // Copy the contents of the file to the request stream. System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] fileContents = Encoding.GetEncoding("iso8859-1").GetBytes(json); //and now plug that into your example try { Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); } catch { } request.ContentLength = fileContents.Length; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); response.Close(); return("( http://inaltum.futebol.servicos.ws/" + sFile + " )Complete status :" + response.StatusDescription); } else { return("erro ao gerar dados"); } }
private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { string filePath = openFileDialog1.FileName; string directory = Path.GetDirectoryName(filePath); string name = Path.GetFileName(filePath); string fileExt = Path.GetExtension(name); //MessageBox.Show(name); //MessageBox.Show(filePath); <---These are for debugging purposes only //MessageBox.Show(directory); if (fileExt == ".png" || fileExt == ".jpg" || fileExt == ".jpeg") { try { string server = "ftp://jayyeah977.no-ip.org/"; string username = "******"; string password = "******"; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(server + name); request.Method = WebRequestMethods.Ftp.UploadFile; request.UseBinary = true; request.Credentials = new NetworkCredential(username, password); byte[] fileContents = File.ReadAllBytes(directory + "/" + name); request.ContentLength = fileContents.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); } FtpWebResponse response = (FtpWebResponse)request.GetResponse(); MessageBox.Show("Upload File Complete", response.StatusDescription); response.Close(); db_connection(); string query = "UPDATE users SET imagePath = '" + server + name + "' WHERE username = '******';"; MySqlCommand cmd = new MySqlCommand(query, connect); MySqlDataReader readR = cmd.ExecuteReader(); while (readR.Read()) { } connect.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } else { MessageBox.Show("You may only upload in the png, jpg or jpeg image formats!"); } loadProfileImage(); }
public AppendFileStream(FtpWebRequest request) { request.Method = WebRequestMethods.Ftp.AppendFile; ftpStream = request.GetRequestStream(); }
public static void UploadUserInformation(Settings_Permanent settings) { if (settings == null || m_BackgroundWorker.IsBusy) { return; } m_Settings = settings; string fileName = GenerateFileName(); string uploadPath = Code.UploadCode.UploadDirectoryPath + fileName; string userName = Code.UploadCode.userName; string pass = Code.UploadCode.Code; string dataToUpload = settings.UsersInfoToUpload; bool isUploadSuccessful = false; m_BackgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(delegate(object sender, System.ComponentModel.DoWorkEventArgs e) { if (m_CurrentCulture != null) { System.Threading.Thread.CurrentThread.CurrentUICulture = m_CurrentCulture; } System.IO.MemoryStream memoryStream = null; System.IO.Stream stream = null; try { byte[] byteArray = Encoding.UTF8.GetBytes(dataToUpload); memoryStream = new System.IO.MemoryStream(byteArray); // Create FtpWebRequest object FtpWebRequest ftpRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(uploadPath)); // Provide username and password ftpRequest.Credentials = new System.Net.NetworkCredential(userName, pass); // after a command is executed, do not keep connection alive ftpRequest.KeepAlive = false; ftpRequest.Timeout = 30000; // Specify the command to be executed ftpRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile; ftpRequest.UseBinary = true; ftpRequest.ContentLength = memoryStream.Length; // buffer size is kept 2kb. int bufferLength = 2048; byte[] buff = new byte[bufferLength]; stream = ftpRequest.GetRequestStream(); // Read the memory stream 2kb at a time and copy to ftpStream int dataLength = memoryStream.Read(buff, 0, bufferLength); while (dataLength != 0) { // Write Content from the memory stream to the FTP Upload Stream. stream.Write(buff, 0, dataLength); dataLength = memoryStream.Read(buff, 0, bufferLength); } isUploadSuccessful = true; } catch (System.Exception ex) { m_Settings.UploadAttemptsCount++; m_Settings.SaveSettings(); Console.WriteLine(ex.ToString()); ProjectView.ProjectView.WriteToLogFile_Static(ex.ToString()); } finally { if (stream != null) { stream.Close(); stream.Dispose(); } if (memoryStream != null) { memoryStream.Close(); memoryStream.Dispose(); } } }); m_BackgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(delegate(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { if (m_CurrentCulture != null) { System.Threading.Thread.CurrentThread.CurrentUICulture = m_CurrentCulture; } if (!isUploadSuccessful) { return; } try { FtpWebRequest ftpRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(uploadPath)); ftpRequest.Credentials = new System.Net.NetworkCredential(userName, pass); ftpRequest.KeepAlive = false; ftpRequest.Timeout = 20000; ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize; ftpRequest.UseBinary = true; // if successful then update settings for the same if (ftpRequest.GetResponse().ContentLength > 0) { Console.WriteLine("registered"); //m_Settings.UsersInfoToUpload = Registered; m_Settings.RegistrationComplete = true; m_Settings.SaveSettings(); //MessageBox.Show("done"); } else { m_Settings.UploadAttemptsCount++; m_Settings.SaveSettings(); } } catch (System.Exception ex) { m_Settings.UploadAttemptsCount++; m_Settings.SaveSettings(); Console.WriteLine(ex.ToString()); ProjectView.ProjectView.WriteToLogFile_Static(ex.ToString()); } }); m_BackgroundWorker.RunWorkerAsync(); }
private void toolStripButtonTransferer_Click(object sender, EventArgs e) { Form activeChild = this.ActiveMdiChild; if (activeChild == null) { return; } if (!(activeChild is MainForm)) { return; } MainForm karelForm = (MainForm)activeChild; if (karelForm.KarelFileEnv.PcFullFileName == null || karelForm.KarelFileEnv.PcFullFileName == string.Empty) { MessageBox.Show("Pas de fichier compilé."); return; } FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(new Uri(Properties.Settings.Default.FTPServer + karelForm.KarelFileEnv.PcFileName)); ftpClient.Credentials = new System.Net.NetworkCredential(Properties.Settings.Default.FTPUser, ""); ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile; ftpClient.UseBinary = true; ftpClient.KeepAlive = false; ftpClient.Timeout = 10000; ftpClient.UsePassive = Properties.Settings.Default.PassiveMode; //ftpClient.Timeout = 2000; System.IO.FileInfo fi = new System.IO.FileInfo(karelForm.KarelFileEnv.PcFullFileName); ftpClient.ContentLength = fi.Length; byte[] buffer = new byte[4097]; int bytes = 0; int total_bytes = (int)fi.Length; System.IO.FileStream fs = fi.OpenRead(); System.IO.Stream rs = ftpClient.GetRequestStream(); while (total_bytes > 0) { bytes = fs.Read(buffer, 0, buffer.Length); rs.Write(buffer, 0, bytes); total_bytes = total_bytes - bytes; } //fs.Flush(); fs.Close(); rs.Close(); FtpWebResponse uploadResponse; string value = ""; try { uploadResponse = (FtpWebResponse)ftpClient.GetResponse(); value = uploadResponse.StatusDescription; uploadResponse.Close(); } catch (Exception ex) { } MessageBox.Show(value); }
private void backgroundWorker1_DoWork_1(object sender, DoWorkEventArgs e) { if (checkdown.Checked == true) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", Server, Filename))); request.Credentials = new NetworkCredential(Username, Password); request.Method = WebRequestMethods.Ftp.DownloadFile; //Download Method //Get some data form the source file like the zise and the TimeStamp. every data you request need to be a different request and response FtpWebRequest request1 = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", Server, Filename))); request1.Credentials = new NetworkCredential(Username, Password); request1.Method = WebRequestMethods.Ftp.GetFileSize; //GetFileze Method FtpWebResponse response = (FtpWebResponse)request1.GetResponse(); double total = response.ContentLength; response.Close(); FtpWebRequest request2 = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", Server, Filename))); request2.Credentials = new NetworkCredential(Username, Password); request2.Method = WebRequestMethods.Ftp.GetDateTimestamp; //GetTimestamp Method FtpWebResponse response2 = (FtpWebResponse)request2.GetResponse(); DateTime modify = response2.LastModified; response2.Close(); Stream ftpstream = request.GetResponse().GetResponseStream(); FileStream fs = new FileStream(localdest, FileMode.Create); // Method to calculate and show the progress. byte[] buffer = new byte[1024]; int byteRead = 0; double read = 0; do { byteRead = ftpstream.Read(buffer, 0, 1024); fs.Write(buffer, 0, byteRead); read += (double)byteRead; double percentage = read / total * 100; backgroundWorker1.ReportProgress((int)percentage); }while (byteRead != 0); ftpstream.Close(); fs.Close(); } else { //Upload Method. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", Server, Filename))); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(Username, Password); Stream ftpstream = request.GetRequestStream(); FileStream fs = File.OpenRead(Fullname); // Method to calculate and show the progress. byte[] buffer = new byte[1024]; double total = (double)fs.Length; int byteRead = 0; double read = 0; do { byteRead = fs.Read(buffer, 0, 1024); ftpstream.Write(buffer, 0, byteRead); read += (double)byteRead; double percentage = read / total * 100; backgroundWorker1.ReportProgress((int)percentage); }while (byteRead != 0); fs.Close(); ftpstream.Close(); } }
void SaveReport(string name, Frame[] data) { string reportFilePath = Application.dataPath + "/../Records/" + name + ".rpt"; FileStream output = new FileStream(reportFilePath, FileMode.Create); float[] l_reportData = new float[data.Length * 20 * 3]; //20 joints 3 coords int l_idx = 0; foreach (var l_frame in data) { SaveReportNode(l_reportData, JointType.AnkleLeft, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.AnkleRight, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.ElbowLeft, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.ElbowRight, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.FootLeft, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.FootRight, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.HandLeft, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.HandRight, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.Head, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.SpineBase, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.HipLeft, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.HipRight, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.KneeLeft, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.KneeRight, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.SpineShoulder, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.ShoulderLeft, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.ShoulderRight, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.SpineMid, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.WristLeft, l_idx, l_frame); l_idx += 3; SaveReportNode(l_reportData, JointType.WristRight, l_idx, l_frame); l_idx += 3; } byte[] l_byteArr = new byte[l_reportData.Length * sizeof(float)]; Buffer.BlockCopy(l_reportData, 0, l_byteArr, 0, l_reportData.Length); output.Write(l_byteArr, 0, l_byteArr.Length); output.Close(); //send data to server if online if (VTenvironment.Instance != null) { if (!VTenvironment.Instance.isOffline) { FtpWebRequest l_rqst = (FtpWebRequest)WebRequest.Create("ftp://194.87.93.103:21/" + name + ".rpt"); l_rqst.Method = WebRequestMethods.Ftp.UploadFile; l_rqst.Credentials = new NetworkCredential(VTenvironment.Instance.userName, VTenvironment.Instance.password); Stream l_rqstStream = l_rqst.GetRequestStream(); l_rqstStream.Write(l_byteArr, 0, l_byteArr.Length); l_rqstStream.Close(); { FtpWebResponse l_resp = null; try { l_resp = (FtpWebResponse)l_rqst.GetResponse(); } catch (System.Exception e) { Debug.Log(e.Message); return; } finally { if (l_resp != null) { Debug.Log(l_resp.StatusDescription); l_resp.Close(); ((System.IDisposable)l_resp).Dispose(); } } } } } }
private void button8_Click(object sender, EventArgs e) { try { if (textBox7.Text == "1122123qQ") { //1.,вычилсяем хээш сумму текущего файла string hash1 = hash_value("TreeCadN.dll"); // MessageBox.Show(hash1);//asdsadas //2. отправляем файл на сервер FileInfo toUpload = new FileInfo("TreeCadN.dll"); FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ecad.giulianovars.ru/public/TreeCadN//" + toUpload.Name); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential("ecad_ftp", "bFqeNo4Xp2"); Stream ftpStream = request.GetRequestStream(); FileStream fileStream = File.OpenRead("TreeCadN.dll"); byte[] buffer = new byte[1024]; int bytesRead = 0; do { bytesRead = fileStream.Read(buffer, 0, 1024); ftpStream.Write(buffer, 0, bytesRead); }while (bytesRead != 0); fileStream.Close(); ftpStream.Close(); //3. скачиваем файл WebClient client = new WebClient(); var url = "http://ecad.giulianovars.ru/TreeCadN/TreeCadN.dll"; string tmppath = Path.GetTempPath() + @"\TreeCadN.dll"; client.DownloadFile(url, tmppath);//скачаем новую // 4. вычисляем хэшш string hash2 = hash_value(tmppath); // MessageBox.Show(hash2);//asdsadas // 5. проверяем сходится ли хэш if (hash1 == hash2) { client = new WebClient(); url = "http://ecad.giulianovars.ru/TreeCadN/hash_prov.php?type=2&hash=" + hash1; client.DownloadString(url); MessageBox.Show("Сумма сходится = " + hash1); } else { MessageBox.Show("ERROR Сумма разная = " + hash1 + "\r\n" + hash2); } } else { MessageBox.Show("Неверный пароль"); } } catch (Exception err) { MessageBox.Show(err.Message); } }
public IActionResult Contest2(List <IFormFile> files) { //var Server = "ftp://127.0.0.1"; long size = files.Sum(f => f.Length); var email = _userManager.GetUserName(User); foreach (var formFile in files) { //var filename = Guid.NewGuid() + formFile.FileName; //string filepath = Path.Combine("ftp://166.62.26.27/", filename); //string localpath = Path.Combine("./Files/" + filename); //var stream = new FileStream(localpath, FileMode.Create); //formFile.CopyTo(stream); //stream.Close(); ////Upload Method. //FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}", filepath))); //request.Method = WebRequestMethods.Ftp.UploadFile; //request.Credentials = new NetworkCredential("*****@*****.**", "wgi3L76?"); //request.UseBinary = true; //request.UsePassive = true; //Stream ftpstream = request.GetRequestStream(); //FileStream fs = System.IO.File.OpenRead(localpath); //byte[] buffer = new byte[1024]; //int byteRead = 0; //double read = 0; ////FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.ReadWrite); //double total = (double)fs.Length; //do //{ // byteRead = fs.Read(buffer, 0, 1024); // if (byteRead > 0) // { // ftpstream.Write(buffer, 0, byteRead); // read += (double)byteRead; // } // //double percentage = read / total * 100; // //backgroundWorker1.ReportProgress((int)percentage); //} //while (byteRead != 0); //fs.Close(); //ftpstream.Close(); //System.IO.File.Delete(localpath); //if (total != 0) //{ // var user = new contest2Table // { // Email = email, // fileToUpload = filename, // submittedfile = true // }; // _context.contest2Table.Add(user); // _context.SaveChanges(); //} string ftpServer = "ftp://166.62.26.27/"; string ftpUserName = "******"; string ftpUserPass = "******"; string fileName = Guid.NewGuid().ToString() + formFile.FileName; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + fileName); request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential(ftpUserName, ftpUserPass); // Copy the contents of the file to the request stream. byte[] fileContents; using (StreamReader sourceStream = new StreamReader(formFile.OpenReadStream())) { fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); } if (fileContents.Length != 0) { request.ContentLength = fileContents.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(fileContents, 0, fileContents.Length); } var user = new contest2Table { Email = email, fileToUpload = fileName, submittedfile = true }; _context.contest2Table.Add(user); _context.SaveChanges(); } } //var filePaths = new List<string>(); //foreach (var formFile in files) //{ // if (formFile.Length > 0) // { // // full path to file in temp location // //var filePath = Path.GetTempFileName(); //we are using Temp file name just for the example. Add your own file path. // var filePath = Path.Combine("C:/Users/gunja/source/repos/ContestApplication/ContestApplication/Files/",formFile.FileName); // //filePaths.Add(filePath); // using (var stream = new FileStream(filePath, FileMode.Create)) // { // var user = new contest2Table // { // Email = email, // fileToUpload = filePath, // submittedfile = true // }; // _context.contest2Table.Add(user); // _context.SaveChanges(); // formFile.CopyTo(stream); // } // } //} // process uploaded files // Don't rely on or trust the FileName property without validation. return(Redirect("/Home/Index")); }
/// <summary> /// 上传文件到FTP服务器(断点续传) /// </summary> /// <param name="localFile">本地文件全路径名称</param> /// <param name="remoteFile">远程文件</param> /// <param name="brokenOpen ">是否支持断点续传,默认不使用断点续传</param> /// <param name="updateProgress">报告进度的处理(第一个参数:拥有者对象,第二个参数:总大小,第三个参数:当前进度,第四个参数:下载速度 /秒)</param> /// <returns></returns> public bool UploadFile(string localFile, string remoteFile, bool brokenOpen = false, Action<object, long, long, double> updateProgress = null) { try { state = 0; AutoCreateDir(remoteFile); FileInfo fileInf = new FileInfo(localFile); long fileSize = fileInf.Length; long remoteFileSize = GetFileSize(remoteFile); if (remoteFileSize < 0) { remoteFileSize = 0; //文件不存在 } long startByte = 0; if (brokenOpen) { if (remoteFileSize > fileSize) { //服务器上文件比本地还要大,说明出异常了 throw new Exception("服务器文件大小出现异常,请检查后重新上传!"); } startByte = remoteFileSize; } else { if (remoteFileSize > 0) { DeletFile(remoteFile); } remoteFileSize = 0; } init(remoteFile); ftpReq.Method = brokenOpen ? WebRequestMethods.Ftp.AppendFile : WebRequestMethods.Ftp.UploadFile; ftpReq.ContentLength = fileInf.Length; using (FileStream fs = fileInf.OpenRead()) { using (Stream strm = ftpReq.GetRequestStream()) { DateTime dtBegin = DateTime.Now; fs.Seek(startByte, 0); int contentLen = fs.Read(buffer, 0, BLOCK_SIZE); TotalSize = fileSize; CompleteSize = startByte; if (contentLen == 0) { updateProgress?.Invoke(Owner, fileSize, startByte, 0);//更新进度条 } // 流内容没有结束 while (contentLen != 0) { if (state > 0) break; // 把内容从file stream 写入 upload stream startByte += contentLen; strm.Write(buffer, 0, contentLen); contentLen = fs.Read(buffer, 0, BLOCK_SIZE); TimeSpan ts = DateTime.Now.Subtract(dtBegin); double speed = 0; if (ts.Seconds > 0) { speed = (startByte - remoteFileSize) / ts.Seconds; } Speed = speed; updateProgress?.Invoke(Owner, fileSize, startByte, speed);//更新进度条 } } } return true; } catch (Exception ex) { string info = "上传文件失败:" + ex.Message; LogLocal.log().SaveLog(new LogEntity(info, LogType.Plat, LogLevel.ERROR)); throw new Exception(info); } finally { if (state == 2) { DeletFile(remoteFile); } } }
public void UploadResume(string localDirectory, string localFilename, string remoteDirectory, string remoteFileName) { _abort = false; FileInfo fi = new FileInfo(Path.Combine(localDirectory, localFilename)); long remoteFileSize = 0; FtpWebRequest request = null; long totalBytesSend = 0; request = WebRequest.Create(new Uri("ftp://" + _host + ":" + Port + "/" + remoteDirectory + "/" + remoteFileName)) as FtpWebRequest; request.Credentials = new NetworkCredential(UserName, Password); request.Timeout = TimeOut; request.UsePassive = UsePassive; request.KeepAlive = KeepAlive; try { if (this.FileExists(remoteDirectory, remoteFileName, out remoteFileSize)) { request.Method = WebRequestMethods.Ftp.AppendFile; } else { WebException webException; if (!this.DirectoryExits(remoteDirectory, out webException)) { var directoryCreated = this.CreateDirectory(remoteDirectory, out webException); }//if request.Method = WebRequestMethods.Ftp.UploadFile; } request.ContentLength = fi.Length - remoteFileSize; request.UsePassive = true; using (Stream requestStream = request.GetRequestStream()) { using (FileStream logFileStream = new FileStream(Path.Combine(localDirectory, localFilename), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { StreamReader fs = new StreamReader(logFileStream); fs.BaseStream.Seek(remoteFileSize, SeekOrigin.Begin); byte[] buffer = new byte[BUFFER_SIZE]; int readBytes = 0; do { readBytes = fs.BaseStream.Read(buffer, 0, BUFFER_SIZE); requestStream.Write(buffer, 0, readBytes); if (UploadProgressChanged != null && !_abort) { UploadProgressChanged(this, new UploadProgressChangedLibArgs(fs.BaseStream.Position, fs.BaseStream.Length)); } //System.Threading.Thread.Sleep(500); } while (readBytes != 0 && !_abort); //_fileStreams.Remove( fs ); requestStream.Close(); totalBytesSend = fs.BaseStream.Length; fs.Close(); logFileStream.Close(); Thread.Sleep(100); } //using } //using //Console.WriteLine( "Done" ); if (UploadFileCompleted != null && !_abort) { var uploadFileCompleteArgs = new UploadFileCompletedEventLibArgs(totalBytesSend, TransmissionState.Success); UploadFileCompleted(this, uploadFileCompleteArgs); } //if } //try catch (WebException webException) { if (UploadFileCompleted != null && !_abort) { UploadFileCompleted(this, new UploadFileCompletedEventLibArgs(totalBytesSend, TransmissionState.Failed, webException)); } //if } //catch catch (Exception exp) { if (UploadFileCompleted != null && !_abort) { UploadFileCompleted(this, new UploadFileCompletedEventLibArgs(totalBytesSend, TransmissionState.Failed, exp)); } //if } //catch } //method
public bool Upload(Stream sourceStream, string targetFilename) { // validate the target file string target; if (string.IsNullOrEmpty(targetFilename)) { throw new ApplicationException("Target filename must be specified"); } if (targetFilename.Contains("/")) { // treat as full path target = AdjustDir(targetFilename); } else { target = CurrentDirectory + targetFilename; } //string URI = Hostname + targetFilename; string URI = Hostname + target; //perform copy FtpWebRequest ftp = GetRequest(URI); //Set request to upload a file in binary ftp.Method = WebRequestMethods.Ftp.UploadFile; ftp.UseBinary = true; //Notify FTP of the expected size ftp.ContentLength = sourceStream.Length; //create byte array to store: ensure at least 1 byte! const int BufferSize = 2048; byte[] content = new byte[BufferSize - 1 + 1]; int dataRead; //open file for reading using (sourceStream) { try { sourceStream.Position = 0; //open request to send using (Stream rs = ftp.GetRequestStream()) { do { dataRead = sourceStream.Read(content, 0, BufferSize); rs.Write(content, 0, dataRead); } while (!(dataRead < BufferSize)); rs.Close(); } return(true); } catch // (Exception) { } finally { //ensure file closed sourceStream.Close(); ftp = null; } } return(false); }
/// <summary> /// Выложить картинки на FTP /// </summary> /// <param name="presInfo">Информация о презентации</param> public void UploadImages(PresentationInfo presInfo) { if (presInfo == null) { throw new ArgumentNullException("presentation info is not set"); } for (int index = 0; index < presInfo.SlidersInfo.Count; index++) { SlideInfo slideInfo = presInfo.SlidersInfo[index]; //if (!String.IsNullOrEmpty(slideInfo.ImageNameServerSmall)) //{ // UploadImage(slideInfo.ImageNameClientSmall, String.Format("{0}/{1}", SmallImageServerDir, slideInfo.ImageNameServerSmall)); //} CreateFtpFolder(Path.Combine(_UploadImagesBaseDir, FilesServerDir, presInfo.DbId.ToString())); if (!String.IsNullOrEmpty(slideInfo.ImageNameClientAverage)) { CreateFtpFolder(Path.Combine(_UploadImagesBaseDir, FilesServerDir, presInfo.DbId.ToString(), "268")); UploadImage( Path.Combine(SlideInfo.GetLocalImageDirectoryAbsolutePath(presInfo.DbId, "268"), slideInfo.ImageNameClientAverage), String.Format("{0}/{1}/268/{2}", FilesServerDir, presInfo.DbId, slideInfo.ImageNameClientAverage)); } if (!String.IsNullOrEmpty(slideInfo.ImageNameClientBig)) { CreateFtpFolder(Path.Combine(_UploadImagesBaseDir, FilesServerDir, presInfo.DbId.ToString(), "653")); UploadImage( Path.Combine(SlideInfo.GetLocalImageDirectoryAbsolutePath(presInfo.DbId, "653"), slideInfo.ImageNameClientBig), String.Format("{0}/{1}/653/{2}", FilesServerDir, presInfo.DbId, slideInfo.ImageNameClientBig)); } if (UploadImageCompleteCallback != null) { UploadImageCompleteCallback(this, new UploadImageCompliteInfo { TotalImagesCount = presInfo.SlidersInfo.Count, CurrentImageNumber = index + 1 }); } } try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(String.Format("ftp://{0}/{1}/{2}/{3}", _FTPHost, Path.Combine(_UploadImagesBaseDir, FilesServerDir), presInfo.DbId, presInfo.UrlNews + ".zip")); request.UseBinary = true; request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(_UserName, _UserPassword); Stream requestStream = request.GetRequestStream(); using (FileStream sourse = new FileStream(presInfo.ZipPresentationAbsoluteLocation, FileMode.Open)) { int count = 0; int lenght = 0; byte[] buffer = new byte[4096]; while ((count = sourse.Read(buffer, 0, 4096)) != 0) { lenght += count; if (OnUploadPresentationBlockCallbak != null) { OnUploadPresentationBlockCallbak(this, new UploadPresentationBlockInfo { PercentProgress = (int)(lenght * 100 / sourse.Length) }); } requestStream.Write(buffer, 0, count); } requestStream.Close(); } File.Delete(presInfo.ZipPresentationAbsoluteLocation); } catch (Exception ex) { throw new Exception(String.Format("Во время загрузки файла с презентацией {0} на сервер, возникла ошибка: {1}", presInfo.ServerFileName, ex.Message)); } }
/* Upload File */ public void upload(string remoteFile, string localFile) { try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(user, pass); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; /* Establish Return Communication with the FTP Server */ ftpStream = ftpRequest.GetRequestStream(); /* Open a File Stream to Read the File for Upload */ FileStream localFileStream = new FileStream(localFile, FileMode.OpenOrCreate, FileAccess.Read);// 這邊要加 : FileAccess.Read /* Buffer for the Downloaded Data */ byte[] byteBuffer = new byte[bufferSize]; int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); if(bytesSent == 0) { Debug.LogError("Upload File size is Empty !"); } /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */ try { while (bytesSent != 0) { ftpStream.Write(byteBuffer, 0, bytesSent); bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); Debug.Log(" ***** bytesSent siez = "+ bytesSent); } } catch (Exception ex) { Debug.Log(" ***-1** file siez = "); Console.WriteLine(ex.ToString()); } /* Resource Cleanup */ localFileStream.Close(); ftpStream.Close(); ftpRequest = null; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return; }
public override void ActionAsDestination() { ControllerOfOutput output = ControllerOfOutput.Instance; DirectoryInfo di = new DirectoryInfo(SettingsClass.Instance.GetTmpDirName()); //int localErrorCount = 0; foreach (FileInfo file in di.GetFiles()) { string ftpUriStr = ""; try { ftpUriStr = @"ftp://" + this.ftpUri + "/" + file.Name; FtpWebRequest request = WebRequest.Create(new Uri(string.Format(ftpUriStr))) as FtpWebRequest; request.Method = WebRequestMethods.Ftp.UploadFile; request = this.FtpSet(request); //здесь непосредственно передача int totalReadBytesCount = 0; using (FileStream inputStream = File.OpenRead(file.FullName)) using (Stream outputStream = request.GetRequestStream()) { byte[] buffer = new byte[16384]; int prevByteCount = 0; int readBytesCount; while ((readBytesCount = inputStream.Read(buffer, 0, buffer.Length)) > 0) { outputStream.Write(buffer, 0, readBytesCount); totalReadBytesCount += readBytesCount; double progress = totalReadBytesCount * 100.0 / inputStream.Length; double totalKBytes = Math.Round((double)totalReadBytesCount / 1000, 0); double allKBytes = Math.Round((double)inputStream.Length / 1000, 0); prevByteCount = totalReadBytesCount; output.WriteProgress(String.Format("Progress: {0}% {1} Кб из {2} Кб.", Math.Round(progress, 2).ToString("##0.00"), totalKBytes, allKBytes)); } } this.statistics.incrementFiles(1); this.statistics.incrementBytesWithCut(file.Length); this.statistics.addResult(WorkResult.Success); } catch (Exception ex) { //сперва проверяем, не вылезла ли ошибка только потому, что такой файл уже существует FtpWebRequest request = WebRequest.Create(new Uri(string.Format(ftpUriStr))) as FtpWebRequest; request.Method = WebRequestMethods.Ftp.GetFileSize; request = this.FtpSet(request); try { FtpWebResponse response = (FtpWebResponse)request.GetResponse(); } catch (WebException wex) { FtpWebResponse response = (FtpWebResponse)wex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { string errMsg2 = String.Format("Файл {0} уже существует на ftp-сервере {1}.", file.FullName, ftpUriStr); output.WriteAverageMessage(errMsg2); this.statistics.addMessage(errMsg2); continue; } } string errMsg = String.Format( "Ошибка при передачи файла {0} На сервер {1}. Текст ошибки: {2}", file.Name, ftpUriStr, ex.Message); output.WriteErrors(errMsg); this.statistics.addError(errMsg); return; //localErrorCount++; /* * if (localErrorCount > this.errorCount) * { * throw new FileExchangeException(errMsg); * } * Thread.Sleep(this.sleepBeforeNext); */ } } }
public bool Upload(string src, string dest, int chunksize = 2048) { FileInfo inf = new FileInfo(src); string uri = "ftp://" + server + "/" + dest; Log.STR("Uploading file (" + src + ") to (" + dest + ")"); try { Log.STR("Establishing FTP web request..."); request = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); } catch (System.Exception ex) { Log.STR("Failed with message: \"" + ex.Message + "\""); return(false); } Log.STR("Success"); request.Credentials = new NetworkCredential(username, password); request.KeepAlive = false; request.Method = WebRequestMethods.Ftp.UploadFile; request.UseBinary = true; request.ContentLength = inf.Length; FileStream fs; try { fs = File.Open(src, FileMode.Open); } catch (System.Exception ex) { Log.STR("Failed with message: \"" + ex.Message + "\""); return(false); } byte[] buff = new byte[chunksize]; int contentLen; Log.STR("Starting file upload. File size (" + fs.Length + ") chunk size (" + chunksize + ")"); try { Stream strm = request.GetRequestStream(); contentLen = fs.Read(buff, 0, chunksize); while (contentLen > 0) { Log.STR("Writing file chunk"); strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, chunksize); } strm.Close(); fs.Close(); } catch (System.Exception ex) { Log.STR("Failed with message: \"" + ex.Message + "\""); return(false); } Log.STR("Success."); return(true); }
public static bool ftpUpLoadFile(string remoteFile, string localFile) { Document curDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = curDoc.Database; Editor ed = curDoc.Editor; bool ret = false; try { FtpWebRequest ftpRequest = null; //string host = "ftp://10.9.37.100"; string host = "ftp://10.9.37.21"; bool BinaryMode = true; Stream ftpStream = null; int bufferSize = 8192; string en = System.Web.HttpUtility.UrlEncode(host + remoteFile, Encoding.UTF8); /* Create an FTP Request */ //ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/agileFile/"+remoteFile ); ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + remoteFile); /* Log in to the FTP Server with the User Name and Password Provided */ //Uri u=new Uri() //ftpRequest.Credentials = new NetworkCredential("plmftp", "abc123@"); ftpRequest.Credentials = new NetworkCredential("ftp", "Czz3906270@"); /* When in doubt, use these options */ ftpRequest.UseBinary = BinaryMode; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; //ftpRequest. //文件是否存在//////////////////// /*ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize; * FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse(); * * long fileSize = response.ContentLength; * * response.Close(); * MessageBox.Show(fileSize.ToString()); */ //objReqFtp = null; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; /* Establish Return Communication with the FTP Server */ ftpStream = ftpRequest.GetRequestStream(); /* Open a File Stream to Read the File for Upload */ FileStream localFileStream = new FileStream(localFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); ed.WriteMessage("open file\n"); /* Buffer for the Downloaded Data */ byte[] byteBuffer = new byte[bufferSize]; int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */ try { while (bytesSent != 0) { ftpStream.Write(byteBuffer, 0, bytesSent); bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); } ed.WriteMessage("read file\n"); ret = true; } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } /* Resource Cleanup */ localFileStream.Close(); ftpStream.Close(); ftpRequest = null; } catch (IOException ioex) { ed.WriteMessage(ioex.Message); MessageBox.Show(ioex.ToString() + " " + remoteFile); } catch (System.Exception ex) { MessageBox.Show(ex.ToString() + " " + remoteFile); } return(ret); }
public void EnviarArquivosFTP(DirectoryInfo from, String to, String ext, Boolean server) { String ftp; String user; String pass; if (server) { ftp = Properties.Settings.Default.FTP_SERVER_IP; user = Properties.Settings.Default.FTP_SERVER_USER; pass = Properties.Settings.Default.FTP_SERVER_PASS; } else { ftp = Properties.Settings.Default.FTP_EMPRESA_IP; user = Properties.Settings.Default.FTP_EMPRESA_USER; pass = Properties.Settings.Default.FTP_EMPRESA_PASS; } FileInfo[] files = from.GetFiles(ext); if (files.Length > 0) { //img_tick.Image = Properties.Resources.loader2; //lb_progress.Visible = true; //lb_progress.Text = "CONECTANTO COM O SERVIDOR FTP... "; try { int count = 1; foreach (FileInfo file in files) { FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftp + to + file.Name); request.Credentials = new NetworkCredential(user, pass); request.Method = WebRequestMethods.Ftp.UploadFile; request.KeepAlive = false; request.UseBinary = true; request.Timeout = 60000 * 2; //lb_progress.Text = "ENVIANDO -> " + file.Name + " - " + count + "/" + files.Length; //Thread.Sleep(500); FileStream stream = File.OpenRead(from.ToString() + "\\" + file.Name); Stream reqStream = request.GetRequestStream(); byte[] buffer = new byte[4096 * 2]; int nRead = 0; while ((nRead = stream.Read(buffer, 0, buffer.Length)) != 0) { reqStream.Write(buffer, 0, nRead); } stream.Close(); reqStream.Close(); count++; } } catch (WebException ex) { System.Windows.Forms.MessageBox.Show(ex.ToString(), ex.StackTrace); } DateTime dt = DateTime.Now; string data = (string.Format("{0:dd/MM/yyyy}", dt)); string hora = (string.Format("{0:HH:mm}", dt)); Properties.Settings.Default.LASTEXPORT = "ÚLTIMO ENVIO REALIZADO EM " + data + " ÀS " + hora; Properties.Settings.Default.Save(); Properties.Settings.Default.Reload(); //img_tick.Image = Properties.Resources.tick; //lb_progress.Text = Properties.Settings.Default.LASTEXPORT; } else { MessageBox.Show("Nenhum arquivo para ser enviado.", "Aviso"); } }
/// <summary> /// 上传文件 /// </summary> /// <param name="filestream">文件流</param> /// <param name="filename">文件名</param> /// <param name="ftpPath">文件路径</param> /// <param name="ftpUser">FTP服务器用户名</param> /// <param name="ftpPassword">FTP服务器用户密码</param> public static void UpLoadFile(byte[] filestream, string filename, string ftpPath, string ftpUser, string ftpPassword) { if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename is empty"); } if (ftpUser == null) { ftpUser = ""; } if (ftpPassword == null) { ftpPassword = ""; } //if (!File.Exists(localFile)) //{ // //MyLog.ShowMessage("文件:“" + localFile + "” 不存在!"); // return; //} FtpWebRequest ftpWebRequest = null; MemoryStream localFileStream = null; Stream requestStream = null; try { ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(PathHelper.MergeUrl(ftpPath, filename)); ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword); ftpWebRequest.UseBinary = true; ftpWebRequest.KeepAlive = false; ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile; ftpWebRequest.ContentLength = filestream.Length; int buffLength = 4096; byte[] buff = new byte[buffLength]; int contentLen; //localFileStream = new FileInfo(localFile).OpenRead(); localFileStream = new MemoryStream(filestream); requestStream = ftpWebRequest.GetRequestStream(); contentLen = localFileStream.Read(buff, 0, buffLength); while (contentLen != 0) { requestStream.Write(buff, 0, contentLen); contentLen = localFileStream.Read(buff, 0, buffLength); } } catch (Exception ex) { Logger.LogInfo($"ftp upload failed :{ex}"); throw ex; //MyLog.ShowMessage(ex.Message, "FileUpLoad0001"); } finally { if (requestStream != null) { requestStream.Close(); } if (localFileStream != null) { localFileStream.Close(); } } }
public static string FtpUpload(string sourceFile, string serverPath, string folderPath, string port, string userName, string passWord, string fileNameType, string ftpFileName) { var result = ""; var host = ""; var ftpType = ""; if (fileNameType == "1") { ftpType = "New"; } else if (fileNameType == "1") { ftpType = "Replace"; } else { ftpType = "UnDefind"; } FileInfo fi = new FileInfo(sourceFile); if (fileNameType == "1" || fileNameType == "2") { host = "ftp://" + serverPath + ":" + port + "/" + folderPath + "/" + ftpFileName + fi.Extension; } else { host = "ftp://" + serverPath + ":" + port + "/" + folderPath + "/" + fi.Name; } using (StreamWriter sw = File.AppendText(sourceFile)) { sw.WriteLine(""); } FtpWebRequest request = (FtpWebRequest)WebRequest.Create(host); request.Method = WebRequestMethods.Ftp.AppendFile; request.Credentials = new NetworkCredential(userName, passWord); byte[] fileContents; try { using (StreamReader sourceStream = new StreamReader(sourceFile)) { fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); } request.ContentLength = fileContents.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(fileContents, 0, fileContents.Length); } using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { result = response.StatusDescription; } WriteLog("FtpUpload", sourceFile, serverPath, port, folderPath, userName, "Success", ftpType, ftpFileName + fi.Extension); RemoveLastFile(sourceFile); } catch (Exception ex) { result = ex.Message; WriteLog("FtpUpload", sourceFile, serverPath, port, folderPath, userName, ex.Message, ftpType, ftpFileName); } return(result); }
public override async Task ExportAsync() { using (var dbContext = new DelosDbContext(ConnectionString)) { DirectoryInfo di = new DirectoryInfo(Config.Path); var toDelete = di.GetFiles().Where(f => DateTime.Now.Subtract(f.LastWriteTime).TotalDays > Config.KeepFileDays); foreach (var file in toDelete) { file.Delete(); } var artikli = from a in dbContext.artikal.Where(a => dbContext.kategorija. Where(k => k.aktivna == true).Select(k => k.naziv).Contains(a.kategorija) && a.aktivan == true && a.dostupnost != null && a.dostupnost != "0" && a.cijena_prodajna != null && a.cijena_prodajna != 0).ToList() select a; List <artikal> arts = new List <artikal>(); int duplicates = 0; foreach (var a in artikli) { var existing = arts.FirstOrDefault(x => MatchArtikal(x, a)); if (existing != null) { duplicates++; if ((existing.prioritet != null?existing.prioritet:1000) > (a.prioritet != null?a.prioritet:1000) || (existing.prioritet == a.prioritet && existing.cijena_mp > a.cijena_mp)) { arts.Remove(existing); arts.Add(a); } } else { arts.Add(a); } } var options = new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; var json = JsonSerializer.Serialize(from a in arts select new { a.sifra, a.naziv, a.barkod, a.cijena_mp, a.dostupnost, a.kategorija, a.opis, a.slike }, options); string fileName = "ArtikliWEBSHOP_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".json"; string localFilePath = Path.Combine(Config.Path, fileName); StreamWriter sw = new StreamWriter(localFilePath); await sw.WriteAsync(json); sw.Close(); ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateCertificate); // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Path.Combine(Config.FtpAddress, fileName)); request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential(Config.FtpUsername, Config.FtpPassword); // Copy the contents of the file to the request stream. byte[] fileContents; using (StreamReader sourceStream = new StreamReader(localFilePath)) { fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); } request.ContentLength = fileContents.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(fileContents, 0, fileContents.Length); } using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { Console.WriteLine($"Upload File Complete, status {response.StatusDescription}"); } if (Config.KeepFileDays == 0) { File.Delete(localFilePath); } } }
/// <summary> /// 上传文件 /// </summary> /// <param name="localFileName">本地文件全名</param> /// <param name="targetDir">ftp服务器文件路径</param> /// <param name="targetName">ftp服务器文件名</param> /// <returns></returns> public bool UploadFile(string localFileName, string targetDir, string targetName) { /*判断本地文件是否存在*/ if (!File.Exists(localFileName)) { return(false); } targetName = targetName.Trim(); FileInfo fileInfo = new FileInfo(localFileName); if (fileInfo == null || string.IsNullOrWhiteSpace(targetName) || string.IsNullOrWhiteSpace(hostname)) { return(false); } string URI = "FTP://" + hostname + "/" + targetDir + "/" + targetName; //获取ftp对象。 FtpWebRequest ftp = GetRequest(URI); if (ftp == null) { return(false); } //设置FTP命令 设置所要执行的FTP命令 ftp.Method = WebRequestMethods.Ftp.UploadFile; //指定文件传输的数据类型 ftp.UseBinary = true; ftp.UsePassive = true; //告诉ftp文件大小 ftp.ContentLength = fileInfo.Length; //缓冲大小设置为2KB const int BufferSize = 2048; byte[] content = new byte[BufferSize - 1 + 1]; int dataRead; //打开一个文件流 (System.IO.FileStream) 去读上传的文件 using (FileStream fs = fileInfo.OpenRead()) { try { //把上传的文件写入流 using (Stream rs = ftp.GetRequestStream()) { do { //每次读文件流的2KB dataRead = fs.Read(content, 0, BufferSize); rs.Write(content, 0, dataRead); } while (!(dataRead < BufferSize)); rs.Close(); } } catch { return(false); } finally { fs.Close(); } } ftp = null; return(true); #region /***** * FtpWebResponse * ****/ //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse(); #endregion }
public static void Upload(string localPathFile, bool test = false) { if (test == true) { Load_File("ftp_conf.ini", d_ftp); } try { /*Get Local File Information*/ FileInfo objLocalFile = new FileInfo(localPathFile); /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + d_ftp["Hostname"].ToString() + "/" + d_ftp["Dir"].ToString() + "/" + localPathFile); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(d_ftp["Username"].ToString(), d_ftp["Password"]); /* When in doubt, use these options */ ftpRequest.UseBinary = true; if (Boolean.Parse(d_ftp["Passive"].ToString())) { ftpRequest.UsePassive = true; } ftpRequest.KeepAlive = true; //ftpRequest.Timeout = 1000; //set Time out for request upload ftpRequest.Timeout = 600000 * 3; ftpRequest.ContentLength = objLocalFile.Length; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; /* Establish Return Communication with the FTP Server */ ftpStream = ftpRequest.GetRequestStream(); /* Open a File Stream to Read the File for Upload */ //FileStream remoteFileStream = new FileStream(remoteFile, FileMode.Create); FileStream remoteFileStream = objLocalFile.OpenRead(); /* Buffer for the Uploaded Data */ int bufferSize = (int)remoteFileStream.Length; byte[] byteBuffer = new byte[bufferSize]; int bytesSent = remoteFileStream.Read(byteBuffer, 0, bufferSize); /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */ try { while (bytesSent != 0) { ftpStream.Write(byteBuffer, 0, bytesSent); bytesSent = remoteFileStream.Read(byteBuffer, 0, bufferSize); } } catch (Exception ex) { //messageUploadFile = ex.Message.ToString(); if (test == true) { MessageBox.Show(ex.ToString()); } //Console.WriteLine(ex.ToString()); } /* Resource Cleanup */ remoteFileStream.Close(); ftpStream.Close(); ftpRequest = null; if (test == true) { MessageBox.Show("Successful"); } } catch (Exception ex) { if (test == true) { MessageBox.Show(ex.ToString()); } } }
public static bool Upload(string localFile, string remotePath, bool binary = false) { int i = 1 + remotePath.LastIndexOf('/'); string remoteFilename = remotePath.Substring(i); string remoteAddress = $"ftp://ftp01.servage.net/staffordchristadelphians.org.uk/public_html/{remotePath}.new"; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(remoteAddress); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(ftpUserName, ftpPassword); bool success = false; FtpWebResponse response; if (binary) { request.UseBinary = true; int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; int bytesRead = 0; Stream requestStream = request.GetRequestStream(); try { using (FileStream fs = File.OpenRead(localFile)) { do { bytesRead = fs.Read(buffer, 0, bufferSize); requestStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } } catch (Exception ex) { MessageBox.Show($"Exception during upload: {ex.Message}", "WebWriter", MessageBoxButton.OK, MessageBoxImage.Exclamation); } finally { requestStream.Close(); } } else { try { // Copy the contents of the file to the request stream. using (StreamReader sourceStream = new StreamReader(localFile)) { byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); request.ContentLength = fileContents.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); } } catch (Exception ex) { MessageBox.Show($"Exception during upload: {ex.Message}", "WebWriter", MessageBoxButton.OK, MessageBoxImage.Exclamation); } } response = (FtpWebResponse)request.GetResponse(); if (response.StatusCode != FtpStatusCode.CommandOK && response.StatusCode != FtpStatusCode.ClosingData) { MessageBox.Show($"ftp upload failed.\r\nResponse status was '{response.StatusDescription}'", "WebWriter", MessageBoxButton.OK, MessageBoxImage.Exclamation); } else { success = true; } response.Close(); if (success) { request = (FtpWebRequest)WebRequest.Create(remoteAddress); request.Credentials = new NetworkCredential(ftpUserName, ftpPassword); request.Method = WebRequestMethods.Ftp.Rename; request.RenameTo = remoteFilename; response = (FtpWebResponse)request.GetResponse(); if (response.StatusCode != FtpStatusCode.FileActionOK) { MessageBox.Show($"ftp rename after upload failed.\r\nResponse status was '{response.StatusDescription}'", "WebWriter", MessageBoxButton.OK, MessageBoxImage.Exclamation); } response.Close(); } return(success); }
public void UploadData(string ftpAddressPath, string locationFile, string folder) { try { FtpWebRequest reqFTP = null; Stream ftpStream = null; string[] subDirs = folder.Split('/'); foreach (string subDir in subDirs) { try { ftpAddressPath = ftpAddressPath + subDir + "/"; reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpAddressPath); reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(this.Username, this.Password); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (WebException ex) { FtpWebResponse response = (FtpWebResponse)ex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { //Does not exist } else { throw ex; } } } FileInfo Finfo = new FileInfo(locationFile); this.FtpWebRequest = (FtpWebRequest)FtpWebRequest.Create(ftpAddressPath + Finfo.Name); this.FtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile; // this.FtpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory; this.FtpWebRequest.Credentials = new NetworkCredential(this.Username, this.Password); Stream FtpStream = FtpWebRequest.GetRequestStream(); FileStream Files = File.OpenRead(locationFile); int LengthBuffer = 1024; int ByteRead = 0; byte[] Buffer = new byte[LengthBuffer]; do { ByteRead = Files.Read(Buffer, 0, LengthBuffer); FtpStream.Write(Buffer, 0, ByteRead); } while (ByteRead != 0); Files.Close(); FtpStream.Close(); } catch (WebException ex) { FtpWebResponse response = (FtpWebResponse)ex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { } else { throw ex; } } }
private void button3_Click(object sender, EventArgs e) { if (radioButton1.Checked == true) { for (int i = 0; i < files.Length; i++) { string file = Path.GetFileName(files[i]); File.Copy(files[i], namePathForCopy + @"\\" + file, true); } string[] filesDoCopy = Directory.GetFiles(namePathForCopy); for (int i = 0; i < filesDoCopy.Length; i++) { string f = Path.GetFileName(filesDoCopy[i]); listBox1.Items.Add(f); } MessageBox.Show("Резервное копирование выполнено", "Успешно", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (radioButton2.Checked == true) { string url = ""; string username = ""; string password = ""; if (FTPprofile == "Профиль №1 ") { url = Properties.Settings.Default.ftp1; username = Properties.Settings.Default.ftpName1; password = Properties.Settings.Default.ftpPass1; } if (FTPprofile == "Профиль №2 ") { url = Properties.Settings.Default.ftp2; username = Properties.Settings.Default.ftpName2; password = Properties.Settings.Default.ftpPass2; } if (FTPprofile == "Профиль №3 ") { url = Properties.Settings.Default.ftp3; username = Properties.Settings.Default.ftpName3; password = Properties.Settings.Default.ftpPass3; } for (int i = 0; i < files.Length; i++) { FileInfo fileInfo = new FileInfo(files[i]); FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + "/File%20Worker%20Reserv/" + Path.GetFileName(files[i]))); request.Credentials = new NetworkCredential(username, password); request.KeepAlive = true; request.Method = WebRequestMethods.Ftp.UploadFile; request.UseBinary = true; request.ContentLength = fileInfo.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; FileStream stream = fileInfo.OpenRead(); try { Stream strm = request.GetRequestStream(); contentLen = stream.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = stream.Read(buff, 0, buffLength); } strm.Close(); stream.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } } MessageBox.Show("Резервное копирование выполнено", "Успешно", MessageBoxButtons.OK, MessageBoxIcon.Information); ftpCheckFiles(url, username, password); } }
/* Upload File */ public void upload(string remoteFile, string localFile, string ftpUser, string ftpPassword) { if (_UploadinStarted != null) { _UploadinStarted(); } try { /* Create an FTP Request */ //ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "//" + remoteFile); ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(remoteFile)); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = false; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; /* Establish Return Communication with the FTP Server */ try { ftpStream = ftpRequest.GetRequestStream(); } catch (WebException e) { String status = ((FtpWebResponse)e.Response).StatusDescription; } /* Open a File Stream to Read the File for Upload */ FileStream localFileStream = new FileStream(localFile, FileMode.Open); /* Buffer for the Downloaded Data */ byte[] byteBuffer = new byte[bufferSize]; int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */ try { while (bytesSent != 0) { ftpStream.Write(byteBuffer, 0, bytesSent); bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); if (_UploadProgress != null) { _UploadProgress(); } } if (_UploadinEnded != null) { _UploadinEnded(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Resource Cleanup */ localFileStream.Close(); ftpStream.Close(); ftpRequest = null; if (_fileclosedforupload != null) { _fileclosedforupload(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); MessageBox.Show(ex.Message, Application.ProductName + ": upload", MessageBoxButtons.OK, MessageBoxIcon.Error); if (_Failed != null) { _Failed(ex.Message); } } return; }
//上传文件,传入的路径是本地,目录名默认为空 public static bool upload(String localpath, string dirpath = "") { bool bol = false; string uri = ""; try { FileInfo fileInf = new FileInfo(localpath); //此处需要在上传的时候需要找到服务器中的目录名,没有目录名的话可以不传 if (dirpath == "") { uri = "ftp://" + ftpServerIP + "/" + fileInf.Name; } else { uri = "ftp://" + ftpServerIP + "/" + dirpath + "/" + fileInf.Name; } connect(uri); //连接 // 默认为true,连接不会被关闭 // 在一个命令之后被执行 reqFTP.KeepAlive = false; // 指定执行什么命令 reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // 上传文件时通知服务器文件的大小 reqFTP.ContentLength = fileInf.Length; // 缓冲大小设置为kb int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; // 打开一个文件流(System.IO.FileStream) 去读上传的文件 FileStream fs = fileInf.OpenRead(); try { // 把上传的文件写入流 Stream strm = reqFTP.GetRequestStream(); // 每次读文件流的kb contentLen = fs.Read(buff, 0, buffLength); if (contentLen == 0) { // 流内容没有结束 bol = true; } else { while (contentLen != 0) { // 把内容从file stream 写入upload stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); bol = true; } } // 关闭两个流 strm.Close(); fs.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "上传失败"); } } catch (Exception ex) { MessageBox.Show(ex.Message, "上传失败"); } return(bol); }
public void PassFiles(string fn, string str) { try { // files = new string[] { }; if (rbtnFolder.Checked || rbtnAll.Checked) { str = str + "/"; files = Directory.GetFiles(fn + "/", @"*.*"); } else { files = Directory.GetFiles(fn, @"*.*"); } if (files != null || files.Length < 0) { foreach (string file in files) { Console.WriteLine(ctr.ToString()); fileInf = new FileInfo(file); fileToCreate = "ftp://" + serverUri + str + fileInf.Name; // Create FtpWebRequest object from the Uri provided reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(fileToCreate)); // Provide the WebPermission Credintials reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); // By default KeepAlive is true, where the control connection is not closed // after a command is executed. reqFTP.KeepAlive = false; // Specify the command to be executed. reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // Specify the data transfer type. reqFTP.UseBinary = true; // Notify the server about the size of the uploaded file reqFTP.ContentLength = fileInf.Length; int buffLength = 524288; //int buffLength = 5000; byte[] buff = new byte[buffLength]; int contentLen; // Opens a file stream (System.IO.FileStream) to read the file to be uploaded FileStream fs = fileInf.OpenRead(); try { // Stream to which the file to be upload is written Stream strm = reqFTP.GetRequestStream(); // Read from the file stream 2kb at a time contentLen = fs.Read(buff, 0, buffLength); // Until Stream content ends while (contentLen != 0) { // Write Content from the file stream to the FTP Upload Stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); ////////////// backgroundWorker1_DoWork; } // Close the file stream and the Request Stream strm.Close(); fs.Close(); ///////////////////////////////////////////////////////////////////// //Deletes file after creating/copying in the server if (rbtnAutoDeleteYes.Checked) { deleteFile(); } ctr++; } catch (WebException e) { String status = ((FtpWebResponse)e.Response).StatusDescription; } catch (Exception ex) { //startMove(); if (ex.HResult == -2146233079) { // this.Invoke((MethodInvoker)delegate() { lblMessage.Text = "Invalid username and password"; }); catchStatus = 1; break; } } } } } catch (Exception eeee) { // lblMessage.Text = eeee.Message; // btnStart.Enabled = true; } //lblMessage.Text = ""; }
private static MemoryStream DoSync(FtpWebRequest request, MemoryStream requestBody) { if (requestBody != null) { Stream requestStream = request.GetRequestStream(); requestBody.CopyTo(requestStream); requestStream.Close(); } FtpWebResponse response = (FtpWebResponse)request.GetResponse(); MemoryStream responseBody = new MemoryStream(); response.GetResponseStream().CopyTo(responseBody); response.Close(); return responseBody; }
/* Upload File */ public string upload(string remoteFile, string localFile) { string _result = null; try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + host + "/" + remoteFile); /* Log in to the FTP Server with the User Name and Password Provided */ ftpRequest.Credentials = new NetworkCredential(user, pass); /* When in doubt, use these options */ ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; /* Establish Return Communication with the FTP Server */ ftpStream = ftpRequest.GetRequestStream(); /* Open a File Stream to Read the File for Upload */ /* use openorcreate as just open will overwrite the file if it already exists */ FileStream _localFileStream = new FileStream(localFile, FileMode.OpenOrCreate); /* Buffer for the Downloaded Data */ byte[] _byteBuffer = new byte[bufferSize]; int _bytesSent = _localFileStream.Read(_byteBuffer, 0, bufferSize); /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */ //try //{ while (_bytesSent != 0) { ftpStream.Write(_byteBuffer, 0, _bytesSent); _bytesSent = _localFileStream.Read(_byteBuffer, 0, bufferSize); } //} //catch (Exception ex) { Console.WriteLine(ex.ToString()); } _localFileStream.Close(); } catch (Exception ex) { //Console.WriteLine(ex.ToString()); _result = ex.Message.ToString(); } finally { /* Resource Cleanup */ ftpStream.Flush(); ftpStream.Close(); ftpRequest = null; } return _result; }