/* Download File */ public string download(string remoteFile, string localFile) { string _result = null; 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.DownloadFile; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Get the FTP Server's Response Stream */ ftpStream = ftpResponse.GetResponseStream(); /* Open a File Stream to Write the Downloaded File */ FileStream _localFileStream = new FileStream(localFile, FileMode.Create); /* Buffer for the Downloaded Data */ byte[] _byteBuffer = new byte[bufferSize]; int _bytesRead = ftpStream.Read(_byteBuffer, 0, bufferSize); /* Download the File by Writing the Buffered Data Until the Transfer is Complete */ //try //{ while (_bytesRead > 0) { _localFileStream.Write(_byteBuffer, 0, _bytesRead); _bytesRead = ftpStream.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.Close(); ftpResponse.Close(); ftpRequest = null; } return _result; }
/* List Directory Contents File/Folder Name Only */ public List<string> directoryListSimple(string directory) { List<string> _directoryList = null; string _chr = "|"; try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory); /* 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.ListDirectory; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Establish Return Communication with the FTP Server */ ftpStream = ftpResponse.GetResponseStream(); /* Get the FTP Server's Response Stream */ StreamReader _ftpReader = new StreamReader(ftpStream); /* Store the Raw Response */ string _directoryRaw = null; /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */ while (_ftpReader.Peek() != -1) { _directoryRaw += _ftpReader.ReadLine() + _chr; } _ftpReader.Close(); /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */ _directoryList = _directoryRaw.Split(_chr.ToCharArray()).ToList(); } catch (Exception ex) { //Console.WriteLine(ex.ToString()); _directoryList.Add(ex.Message.ToString()); } finally { /* Resource Cleanup */ ftpStream.Flush(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; } /* Return an Empty string Array if an Exception Occurs */ return _directoryList; }
/* List Directory Contents in Detail (Name, Size, Created, etc.) */ public string[] directoryListDetailed(string directory) { try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory); /* 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.ListDirectoryDetails; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Establish Return Communication with the FTP Server */ ftpStream = ftpResponse.GetResponseStream(); /* Get the FTP Server's Response Stream */ StreamReader ftpReader = new StreamReader(ftpStream); /* Store the Raw Response */ string directoryRaw = null; /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */ try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Resource Cleanup */ ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */ try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Return an Empty string Array if an Exception Occurs */ return new string[] { "" }; }
/// <summary> /// 上传文件,带断点续传 /// </summary> /// <param name="FolderName">目录名</param> /// <param name="FileName">文件名</param> /// <param name="LocalPath">本地路径</param> /// <param name="LocalFile">本地文件名,为空则用FileName</param> /// <param name="Checked">是否对比大小</param> /// <param name="BufferSize">缓存大小</param> /// <returns>执行结果</returns> public bool UpLoadFile(string FolderName, string FileName, string LocalPath, string LocalFile = "", bool Checked = false, int BufferSize = 4096) { try { if (FolderName == null) { FolderName = ""; } if (FileName == null || LocalPath == null) { ErrMsg = "REF unvalid"; return(false); } else if (FileName.Trim() == "" || LocalPath.Trim() == "") { ErrMsg = "REF unvalid"; return(false); } else { FileInfo fi; if (LocalFile.Trim() != "") { fi = new FileInfo(LocalPath + "\\" + LocalFile); } else { fi = new FileInfo(LocalPath + "\\" + FileName); } if (!fi.Exists) { ErrMsg = "File NOT Exists"; return(false); } if (this.Url.Trim() != "") { string str = Url + "/" + FolderName.Trim(); str = str + "/" + FileName; Uri uri = new Uri(str); FtpWebRequest listRequest = (FtpWebRequest)FtpWebRequest.Create(uri); listRequest.Method = WebRequestMethods.Ftp.GetFileSize; listRequest.Timeout = TimeOut; listRequest.KeepAlive = true; listRequest.UseBinary = false; if (account.UserName.Trim() != "") { listRequest.Credentials = account; } FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse(); long upsize = 0; try { string[] res = listResponse.StatusDescription.Replace("\r\n", "").Split(' '); upsize = long.Parse(res[1]); } catch {} listResponse.Close(); listResponse = null; listRequest.Abort(); if (upsize > fi.Length) { listRequest = (FtpWebRequest)FtpWebRequest.Create(uri); listRequest.Method = WebRequestMethods.Ftp.DeleteFile; listRequest.Timeout = TimeOut; if (account.UserName.Trim() != "") { listRequest.Credentials = account; } listResponse = (FtpWebResponse)listRequest.GetResponse(); FtpStatusCode res = listResponse.StatusCode; listResponse.Close(); listResponse = null; listRequest = null; } listRequest = (FtpWebRequest)FtpWebRequest.Create(uri); if (account.UserName.Trim() != "") { listRequest.Credentials = account; } listRequest.Method = WebRequestMethods.Ftp.AppendFile; listRequest.ContentLength = fi.Length; listRequest.Timeout = TimeOut; listRequest.KeepAlive = true; //使用ASCII模式 listRequest.UseBinary = true; //使用主动(port)模式 listRequest.UsePassive = true; byte[] content = new byte[BufferSize]; int dataRead = 0; using (FileStream fs = fi.OpenRead()) { try { using (Stream rs = listRequest.GetRequestStream()) { do { fs.Seek(upsize, SeekOrigin.Begin); dataRead = fs.Read(content, 0, BufferSize); rs.Write(content, 0, dataRead); upsize += dataRead; }while (!(dataRead < BufferSize)); } } catch { } finally { fs.Close(); } } listRequest.Abort(); listRequest = null; if (Checked) { listRequest = (FtpWebRequest)FtpWebRequest.Create(uri); listRequest.Method = WebRequestMethods.Ftp.GetFileSize; listRequest.Timeout = TimeOut; listRequest.KeepAlive = true; listRequest.UseBinary = false; if (account.UserName.Trim() != "") { listRequest.Credentials = account; } listResponse = (FtpWebResponse)listRequest.GetResponse(); upsize = 0; try { string[] res = listResponse.StatusDescription.Replace("\r\n", "").Split(' '); upsize = long.Parse(res[1]); } catch { } listResponse.Close(); listResponse = null; listRequest.Abort(); listRequest = null; if (upsize == fi.Length) { return(true); } else { return(false); } } else { return(true); } } return(false); } } catch (Exception ex) { ErrMsg = ex.Message; return(false); } }
private void bgwExport_DoWork(object sender, DoWorkEventArgs e) { try { //1. get FTP settings string[] FtpInfo; FtpInfo = DIO.ReadFromFile("FtpInfo.txt"); FtpS.Localdest = @"D:\XFFTPfile\Download\" + @"" + FtpS.FileName; FtpS.Server = FtpInfo[0]; FtpS.UserName = FtpInfo[1]; FtpS.Password = FtpInfo[2]; if (FtpS.Upload) { //2. send file to destination FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", FtpS.Server, FtpS.FileName))); request.Method = WebRequestMethods.Ftp.UploadFile;//upload method request.Credentials = new NetworkCredential(FtpS.UserName, FtpS.Password); Stream FtpStream = request.GetRequestStream(); FileStream fs = File.OpenRead(FtpS.FileName); byte[] buffer = new byte[1024]; double total = (double)fs.Length; int ByteRead = 0; double read = 0; do { if (!bgwExport.CancellationPending) { ByteRead = fs.Read(buffer, 0, 1024); FtpStream.Write(buffer, 0, ByteRead); read += (double)ByteRead; double percentage = read / total * 100; bgwExport.ReportProgress((int)percentage); } else if (bgwExport.CancellationPending) { e.Cancel = true; return; } } while (ByteRead != 0); fs.Close(); FtpStream.Close(); } else { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", FtpS.Server, FtpS.FileName))); request.Method = WebRequestMethods.Ftp.DownloadFile;//download method request.Credentials = new NetworkCredential(FtpS.UserName, FtpS.Password); FtpWebRequest request1 = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", FtpS.Server, FtpS.FileName))); request1.Method = WebRequestMethods.Ftp.GetFileSize;//GetFileSize method request1.Credentials = new NetworkCredential(FtpS.UserName, FtpS.Password); FtpWebResponse response1 = (FtpWebResponse)request1.GetResponse(); double total = response1.ContentLength; response1.Close(); FtpWebRequest request2 = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", FtpS.Server, FtpS.FileName))); request2.Method = WebRequestMethods.Ftp.GetDateTimestamp;//GetDateTimestamp method request2.Credentials = new NetworkCredential(FtpS.UserName, FtpS.Password); FtpWebResponse response2 = (FtpWebResponse)request2.GetResponse(); DateTime modify = response2.LastModified; response2.Close(); Stream FtpStream = request.GetResponse().GetResponseStream(); FileStream fs = new FileStream(FtpS.Localdest, FileMode.Create); byte[] buffer = new byte[1024]; //double total = (double)fs.Length; int ByteRead = 0; double read = 0; do { if (!bgwExport.CancellationPending) { ByteRead = FtpStream.Read(buffer, 0, 1024); fs.Write(buffer, 0, ByteRead); read += (double)ByteRead; double percentage = read / total * 100; Thread.Sleep(1000); bgwExport.ReportProgress((int)percentage); } else if (bgwExport.CancellationPending) { e.Cancel = true; return; } } while (ByteRead != 0); fs.Close(); FtpStream.Close(); } } catch (Exception) { bgwExport.CancelAsync(); } }
private void StartFtpDeleteInThread() { try { Thread.Sleep(50); String host = folder.Site.host; String username = folder.Site.username; String pwd = folder.Site.pwd; String targetfolder = folder.Path; if (files != null) { int count = files.Count(); int iFileCount = 0; foreach (var file in files) { string basicProgress = (++iFileCount).ToString() + " of " + count.ToString() + " : " + file; progress.SetProgress(basicProgress); if (this.cancelled) { break; } FtpWebResponse response = null; while (!this.cancelled) { bool success = false; Exception lastException = null; for (int i = 0; i < 4 && !this.cancelled; i++) { try { progress.SetProgress(basicProgress + " - Connecting"); lock (FtpSite.LockInstance()) { string ftpfullpath = "ftp://" + host + targetfolder + "/" + file; FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); ftp.UseBinary = true; ftp.KeepAlive = true; ftp.Method = WebRequestMethods.Ftp.DeleteFile; ftp.Timeout = 2000; ftp.Credentials = new NetworkCredential(username, pwd); response = (FtpWebResponse)ftp.GetResponse(); progress.SetProgress(basicProgress + response.StatusDescription); success = true; } break; } catch (Exception e) { lastException = e; } finally { try { if (response != null) { response.Close(); } } catch (Exception) { } } } if (this.cancelled) { return; } if (!success) { DialogResult keepGoing = MessageBox.Show("Keep Trying? Failed after 4 attempts to delete: " + file + " Exception: " + lastException.Message , "FTP Failure" , MessageBoxButtons.OKCancel , MessageBoxIcon.Error , MessageBoxDefaultButton.Button1); if (keepGoing != DialogResult.OK) { return; // Don't true any more. } } if (success) { break; // Goto next file only on success. } } } } } finally { progress.DoClose(); } }
/// <summary> /// 下载文件 /// </summary> public bool DownloadFile(string filePath, string ftpPath) { if (_isOnline) { Stream ftpStream = null; FileStream fileStream = null; try { if (!Connect(ftpPath)) { return(false); } if (string.IsNullOrEmpty(Path.GetExtension(filePath))) { filePath = filePath + @"\" + Path.GetFileName(ftpPath); } string dirName = Path.GetDirectoryName(filePath); if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse(); ftpStream = _ftpResponse.GetResponseStream(); int buffLength = 2048; byte[] buffer = new byte[buffLength]; int contentLen = ftpStream.Read(buffer, 0, buffLength); int progressLen = 0; fileStream = new FileStream(filePath, FileMode.Create); while (contentLen > 0) { Application.DoEvents(); fileStream.Write(buffer, 0, contentLen); progressLen += contentLen; if (FileProgressEvent != null) { FileProgressEvent(contentLen * 100 / _ftpResponse.ContentLength); } contentLen = ftpStream.Read(buffer, 0, buffLength); } if (FileProgressEvent != null) { FileProgressEvent(100); } return(true); } catch (Exception ex) { return(false); } finally { if (_ftpResponse != null) { _ftpResponse.Close(); _ftpResponse = null; } if (ftpStream != null) { ftpStream.Close(); ftpStream.Dispose(); } if (fileStream != null) { fileStream.Close(); fileStream.Dispose(); } } } else { FileStream ftpStream = null; FileStream fileStream = null; try { if (!CheckFile(ftpPath)) { return(false); } if (string.IsNullOrEmpty(Path.GetExtension(filePath))) { filePath = filePath + @"\" + Path.GetFileName(ftpPath); } string dirName = Path.GetDirectoryName(filePath); if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } ftpStream = new FileStream(_localPath + ftpPath, FileMode.Open); int buffLength = 2048; byte[] buffer = new byte[buffLength]; int contentLen = ftpStream.Read(buffer, 0, buffLength); int progressLen = 0; fileStream = new FileStream(filePath, FileMode.Create); while (contentLen > 0) { fileStream.Write(buffer, 0, contentLen); progressLen += contentLen; if (FileProgressEvent != null) { FileProgressEvent(contentLen * 100 / _ftpResponse.ContentLength); } contentLen = ftpStream.Read(buffer, 0, buffLength); } if (FileProgressEvent != null) { FileProgressEvent(100); } return(true); } catch (Exception ex) { return(false); } finally { if (ftpStream != null) { ftpStream.Close(); ftpStream.Dispose(); } if (fileStream != null) { fileStream.Close(); fileStream.Dispose(); } } } }
/* List Directory Contents in Detail (Name, Size, Created, etc.) */ /// <summary> /// Requests a detailed directory listing from the server which /// includes the name, size, date created, date modified, etc. /// directory variable is currently unused since we were unable to get /// past directory listing. /// </summary> /// <param name="directory">Unused.</param> /// <returns></returns> public string[] directoryListDetailed(string directory) { try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(@"ftp://localhost:21/"); /* 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.ListDirectoryDetails; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); Thread.Sleep(2000);//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX This is NOT the solution, only a bandaid. /* Establish Return Communication with the FTP Server */ ftpStream = ftpResponse.GetResponseStream(); /* Get the FTP Server's Response Stream */ StreamReader ftpReader = new StreamReader(ftpStream); /* Store the Raw Response */ string directoryRaw = null; /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */ try { Console.WriteLine("Peek: " + ftpReader.Peek()); while (ftpReader.Peek() > -1) { directoryRaw += ftpReader.ReadLine() + "|"; Console.WriteLine("Peek: " + ftpReader.Peek()); Console.WriteLine("Raw Directory" + directoryRaw); } } catch (Exception ex) { Console.WriteLine("Exception in ftpClient directoryListDetailed\nAttempt to read a line" + ex.ToString()); } /* Resource Cleanup */ ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */ try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return(directoryList); } catch (Exception ex) { Console.WriteLine("Exception in ftpClient directoryListDetailed\nTrying to get directory as a string" + ex.ToString()); } } catch (Exception ex) { Console.WriteLine("Exception in ftpClient directoryListDetailed\nFull try catch" + ex.ToString()); } /* Return an Empty string Array if an Exception Occurs */ return(new string[] { "" }); }
public static bool UploadFiletoFtp(string fileName, Uri uploadUrl, string user, string pswd) { Stream requestStream = null; FileStream fileStream = null; FtpWebResponse uploadResponse = null; try { FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uploadUrl); uploadRequest.Method = WebRequestMethods.Ftp.UploadFile; ICredentials credentials = new NetworkCredential(user, pswd); uploadRequest.Credentials = credentials; requestStream = uploadRequest.GetRequestStream(); fileStream = File.Open(fileName, FileMode.Open); byte[] buffer = new byte[1024]; while (true) { var bytesRead = fileStream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { break; } requestStream.Write(buffer, 0, bytesRead); } requestStream.Close(); uploadResponse = (FtpWebResponse)uploadRequest.GetResponse(); Property.Remarks = "File :'" + fileName + "' has been uploaded to '" + uploadUrl + "'."; } catch (UriFormatException ex) { Property.Remarks = "Error: " + ex.Message; return(false); } catch (IOException ex) { Property.Remarks = "Error: " + ex.Message; return(false); } catch (WebException ex) { Property.Remarks = "Error: " + ex.Message; return(false); } finally { if (uploadResponse != null) { uploadResponse.Close(); } if (fileStream != null) { fileStream.Close(); } if (requestStream != null) { requestStream.Close(); } } return(true); }
public IResponse GetResponse() { return(new FtpWebResponseWrapper((FtpWebResponse)ftpWebRequest?.GetResponse())); }
void buttonGetFile_Click(object sender, RoutedEventArgs e) { Cursor currentCursor = this.Cursor; FtpWebResponse response = null; Stream inStream = null; Stream outStream = null; try { this.Cursor = Cursors.Wait; Uri baseUri = new Uri(textServer.Text); string fileName = listFiles.SelectedItem.ToString().Trim(); string fullFileName = System.IO.Path.Combine(serverDirectory, fileName); Uri uri = new Uri(baseUri, fullFileName); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri); request.Credentials = new NetworkCredential( textUserName.Text, passwordBox.Password); request.Method = WebRequestMethods.Ftp.DownloadFile; request.UseBinary = checkBoxBinary.IsChecked ?? false; response = (FtpWebResponse)request.GetResponse(); inStream = response.GetResponseStream(); SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.FileName = fileName; if (saveFileDialog.ShowDialog() == true) { outStream = File.OpenWrite(saveFileDialog.FileName); byte[] buffer = new byte[8192]; int size = 0; while ((size = inStream.Read(buffer, 0, 8192)) > 0) { outStream.Write(buffer, 0, size); } } } catch (WebException ex) { MessageBox.Show(ex.Message, "Error FTP Client", MessageBoxButton.OK, MessageBoxImage.Error); } finally { if (inStream != null) { inStream.Close(); } if (outStream != null) { outStream.Close(); } if (response != null) { response.Close(); } this.Cursor = currentCursor; } }
/// <summary> /// Download Stream /// </summary> /// <param name="path"></param> /// <returns></returns> public Stream DownloadStream(string path) { FtpWebRequest request = GetRequest(WebRequestMethods.Ftp.DownloadFile, path); return(request.GetResponse().GetResponseStream()); }
private static void UpdateCheckerOld(string ip) { Clear(); Dialog.MessageBox("Checking For Updates...", "Please Wait...", ConsoleColor.Blue); var appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); var appdataFolder = $"{appdata}\\MinecraftModUpdater\\"; var applicationPath = $"{appdata}\\MinecraftModUpdater\\Application_Updater.exe"; if (!Directory.Exists(appdataFolder)) { Directory.CreateDirectory(appdataFolder); } if (!File.Exists(applicationPath)) { var client = new WebClient(); client.Credentials = new NetworkCredential("server", "abc"); var data = client.DownloadData( $"ftp://{ip}:21/projectFolder/Application_Updater/Application_Updater.exe"); var stream = File.Create(applicationPath); stream.Write(data, 0, data.Length); stream.Close(); } FtpWebRequest request = (FtpWebRequest)WebRequest.Create($"ftp://{ip}:21/projectFolder/MinecraftModUpdater2/versionData/"); request.Credentials = new NetworkCredential("server", "abc"); request.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException()); string line = reader.ReadLine(); string result = ""; while (!string.IsNullOrEmpty(line)) { if (line.Contains(".data")) { result = line; } line = reader.ReadLine(); } reader.Close(); response.Close(); string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MinecraftModUpdater\\temp"; using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential("server", "abc"); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } string filePath = folderPath + "\\verData.data"; if (File.Exists(filePath)) { File.Delete(filePath); } byte[] data = client.DownloadData($"ftp://{ip}:21/projectFolder/MinecraftModUpdater2/versionData/{result}"); FileStream stream = File.Create(filePath); stream.Write(data, 0, data.Length); stream.Close(); } Version currentVersion = Assembly.GetExecutingAssembly().GetName().Version; Version serverVersion = ReadFromBinaryFile <Version>("temp\\verData.data"); var version = serverVersion.CompareTo(currentVersion); if (version > 0) { var p = new Process { StartInfo = { Arguments = $"\"{Assembly.GetExecutingAssembly().Location}\" \"{Path.GetFileName(Assembly.GetExecutingAssembly().Location)}\" \"{ip}\" \"{version}\"", FileName = applicationPath, UseShellExecute = false } }; p.Start(); Clear(); Dialog.MessageBox("Restarting", "Please Wait", ConsoleColor.Red); Environment.Exit(0); } }
private static void FtpDownloadClient(string target) { try { BackgroundColor = ConsoleColor.DarkCyan; Clear(); Dialog.MessageBox("Checking For Mods...", "Please wait...", ConsoleColor.Blue); FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create($"ftp://{target}/usermods"); ftpWebRequest.Credentials = new NetworkCredential("server", "abc"); ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory; var streamReader = new StreamReader(ftpWebRequest.GetResponse().GetResponseStream() ?? throw new InvalidOperationException()); var directories = new List <string>(); string line = streamReader.ReadLine(); while (!string.IsNullOrEmpty(line)) { if (line.Contains(".jar")) { directories.Add(line); } line = streamReader.ReadLine(); } streamReader.Close(); using (var webClinet = new WebClient()) { webClinet.Credentials = new NetworkCredential("server", "abc"); if (!Directory.Exists($"{AppDataPath}\\.minecraft\\mods")) { Directory.CreateDirectory($"{AppDataPath}\\.minecraft\\mods"); } if (directories.Count > 0) { int updateCounter = 0; foreach (var t in directories) { var trnsFrPth = $"{AppDataPath}\\.minecraft\\" + t.Replace("usermods", "mods"); if (File.Exists(trnsFrPth)) { continue; } Clear(); Dialog.MessageBox($"Downloading {t.Split('/').Last()}", "Upgrading Mods", ConsoleColor.Blue); string path = $"ftp://{target}/{t}"; webClinet.DownloadFile(path, trnsFrPth); updateCounter++; } BackgroundColor = ConsoleColor.DarkCyan; Clear(); if (updateCounter > 0) { string modsUpdated = updateCounter == 1 ? "mod" : "mods"; Dialog.ButtonDialogBox("Complete!", $"The Download/Upgrade is complete!\n({updateCounter}) {modsUpdated} updated\nPress Ok to exit!", ConsoleColor.Blue, MessageBoxButtons.Ok); } else { Dialog.ButtonDialogBox("Already Updated", "You already have all the necessary mods\nrequired to join this server!", ConsoleColor.Blue, MessageBoxButtons.Ok); } Clear(); } else { Clear(); Dialog.ButtonDialogBox("Error", "This server cannot supply\nyou with mod updates as there are\nno mods found within it.", ConsoleColor.Red, MessageBoxButtons.Ok); } } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var selectionIndex = Dialog.SelectionDialogBox("Select Option", "Please Select which option\nyou would like", ConsoleColor.Blue, "Exit", "Open Minecraft Launcher"); switch (selectionIndex) { case 1: var p = new Process() { StartInfo = { FileName = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\Minecraft Launcher\\MinecraftLauncher.exe", } }; p.Start(); break; } } else { Console.Clear(); Dialog.ButtonDialogBox("Finished", "The Download Was successful\npress OK to close this program", ConsoleColor.Blue, MessageBoxButtons.Ok); } Console.Clear(); Dialog.MessageBox("Shutting Down...", "Please Wait", ConsoleColor.Red); Environment.Exit(0); } catch (Exception e) { WriteLine(e); throw; } }
public bool DownloadFileToFTP(string source, string ServerResponse, string destination, string username, string pass, int port, string accountno) { // string filename = Path.GetFileName(source); string MOVEPATH = ""; string ftpfullpath = source; try { if (port > 0) { ftpfullpath = ftpfullpath + ":" + port.ToString(); } if (ftpfullpath.IndexOf("ftp://") == -1) { ftpfullpath = "ftp://" + ftpfullpath; } if (ServerResponse != string.Empty) { if (ServerResponse == "reports") { ftpfullpath = ftpfullpath + @"/reports/"; } else { ftpfullpath = ftpfullpath + @"/Areas/VA009/VA009Docs/" + ServerResponse + @"/"; } } else { ftpfullpath = ftpfullpath + @"/Areas/VA009/VA009Docs/Download/"; } string path = HostingEnvironment.ApplicationPhysicalPath; if (destination == string.Empty) { destination = @"\Areas\VA009\VA009Docs\Response"; } else { string crpath = destination; destination = @"\Areas\VA009\VA009Docs\"; destination += crpath; } path += destination; MOVEPATH = path + @"\" + "Processed"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); Directory.CreateDirectory(path + @"\" + "Processed"); } FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); ftpRequest.Credentials = new NetworkCredential(username, pass); ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse(); StreamReader streamReader = new StreamReader(response.GetResponseStream()); List <string> directories = new List <string>(); string line = streamReader.ReadLine(); while (!string.IsNullOrEmpty(line)) { directories.Add(line); line = streamReader.ReadLine(); } streamReader.Close(); using (WebClient ftpClient = new WebClient()) { ftpClient.Credentials = new System.Net.NetworkCredential(username, pass); for (int i = 0; i <= directories.Count - 1; i++) { if (directories[i].Contains("DMAKS_")) { // string[] filename = ListDirectory(ftpfullpath + "/" + directories[i].ToString(), username, pass); // foreach (var file in filename) // { path = ftpfullpath + @"\" + directories[i].ToString(); string trnsfrpth = HostingEnvironment.ApplicationPhysicalPath + destination + @"\" + directories[i].ToString(); //trnsfrpth=trnsfrpth.Remove((trnsfrpth.Length-3),3); //trnsfrpth= trnsfrpth + "xlsx"; MOVEPATH += @"\" + directories[i].ToString(); if (!Directory.Exists(HostingEnvironment.ApplicationPhysicalPath + destination)) { Directory.CreateDirectory(HostingEnvironment.ApplicationPhysicalPath + destination); } ftpClient.DownloadFile(path, trnsfrpth); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path); request.Credentials = new NetworkCredential(username, pass); request.Method = WebRequestMethods.Ftp.DeleteFile; FtpWebResponse Delresponse = (FtpWebResponse)request.GetResponse(); Delresponse.Close(); GetDataTabletFromCSVFile(trnsfrpth, MOVEPATH); //} } } } return(true); } catch (Exception ex) { return(false); } }
private async void uploadFoto() { waitActivityIndicator.IsRunning = true; var username = "******"; var password = "******"; Stream requestStream = null; FileStream fileStream = null; FtpWebResponse uploadResponse = null; filename = Path.GetFileName(fotoPath); try { FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create("ftp://ftp.hidraulicadelistmo.com/admin/securitb/images" + @"/" + filename); uploadRequest.Method = WebRequestMethods.Ftp.UploadFile; //Since the FTP you are downloading to is secure, send //in user name and password to be able upload the file ICredentials credentials = new NetworkCredential(username, password); uploadRequest.Credentials = credentials; //UploadFile is not supported through an Http proxy //so we disable the proxy for this request. uploadRequest.Proxy = null; //uploadRequest.UsePassive = false; <--found from another forum and did not make a difference requestStream = uploadRequest.GetRequestStream(); fileStream = File.Open(fotoPath, FileMode.Open); byte[] buffer = new byte[1024]; int bytesRead; while (true) { bytesRead = fileStream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { break; } requestStream.Write(buffer, 0, bytesRead); } //The request stream must be closed before getting //the response. requestStream.Close(); uploadResponse = (FtpWebResponse)uploadRequest.GetResponse(); } catch (UriFormatException ex) { await DisplayAlert("Error en Imagen", ex.Message, "Aceptar"); } catch (IOException ex) { await DisplayAlert("Error en Imagen", ex.Message, "Aceptar"); } catch (WebException ex) { await DisplayAlert("Error en Imagen", ex.Message, "Aceptar"); } finally { if (uploadResponse != null) { uploadResponse.Close(); } if (fileStream != null) { fileStream.Close(); } if (requestStream != null) { requestStream.Close(); } } waitActivityIndicator.IsRunning = false; }
/* Get the Size of a File */ public string getFileSize(string fileName) { try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName); /* 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.GetFileSize; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Establish Return Communication with the FTP Server */ ftpStream = ftpResponse.GetResponseStream(); /* Get the FTP Server's Response Stream */ StreamReader ftpReader = new StreamReader(ftpStream); /* Store the Raw Response */ string fileInfo = null; /* Read the Full Response Stream */ try { while (ftpReader.Peek() != -1) { fileInfo = ftpReader.ReadToEnd(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Resource Cleanup */ ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; /* Return File Size */ return fileInfo; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Return an Empty string Array if an Exception Occurs */ return ""; }
/// <summary> /// Download the files and folder form the FTP Server /// </summary> /// <param name="SourceFolder">file location at ftp</param> /// <param name="TargetFolder">download location at local machine</param> /// <param name="fileType">file with extension need to be downloaded, leave empty if you need to download all files</param> public void DownloadFile(string SourceFolder, string targetFolder, string fileType = "") { try { Uri uri = new Uri(_ftpSettings.Value.FTPAddress + "/" + SourceFolder + "/"); // new Uri("ftp://172.18.46.62:21/InSettlementFileFromCrane/"); FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(uri); ftpRequest.Credentials = new NetworkCredential(_ftpSettings.Value.FTPUsername, _ftpSettings.Value.FTPPassword);//new NetworkCredential("ftpuser", "P@ssw0rd"); ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; ftpRequest.Timeout = Timeout.Infinite; ftpRequest.KeepAlive = true; ftpRequest.UseBinary = true; ftpRequest.Proxy = null; ftpRequest.UsePassive = true; var response = ftpRequest.GetResponse(); List <string> directories = new List <string>(); using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { string line = streamReader.ReadLine(); while (!string.IsNullOrEmpty(line)) { directories.Add(line); line = streamReader.ReadLine(); } streamReader.Close(); } using (WebClient ftpClient = new WebClient()) { ftpClient.Credentials = new System.Net.NetworkCredential(_ftpSettings.Value.FTPUsername, _ftpSettings.Value.FTPPassword); ftpClient.Proxy = null; for (int i = 0; i <= directories.Count - 1; i++) { if (string.IsNullOrEmpty(fileType) || directories[i].ToLower().EndsWith(fileType.ToLower())) { string sourcePath = uri + directories[i].ToString(); string transferPath = targetFolder + "\\" + directories[i].ToString(); // @"D:\\New folder\" + directories[i].ToString(); ftpClient.DownloadFile(sourcePath, transferPath); response.Close(); //deleting a file from source FTP FtpWebRequest ftpDeleteRequest = (FtpWebRequest)WebRequest.Create(uri + directories[i].ToString()); ftpDeleteRequest.Credentials = ftpClient.Credentials; ftpDeleteRequest.Method = WebRequestMethods.Ftp.DeleteFile; ftpDeleteRequest.Timeout = Timeout.Infinite; ftpDeleteRequest.KeepAlive = true; ftpDeleteRequest.UseBinary = true; ftpDeleteRequest.Proxy = null; ftpDeleteRequest.UsePassive = true; FtpWebResponse ftpDeleteResponse = (FtpWebResponse)ftpDeleteRequest.GetResponse(); ftpDeleteResponse.Close(); } } } } catch (Exception ex) { throw new Exception("Error while downloading file. Details: " + ex.Message); } }
/* Get the Size of a File */ public string getFileSize(string fileName) { string _result = null; string _fileInfo = null; try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName); /* 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.GetFileSize; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Establish Return Communication with the FTP Server */ ftpStream = ftpResponse.GetResponseStream(); /* Get the FTP Server's Response Stream */ StreamReader _ftpReader = new StreamReader(ftpStream); /* Store the Raw Response */ /* Read the Full Response Stream */ while (_ftpReader.Peek() != -1) { _fileInfo = _ftpReader.ReadToEnd(); } _ftpReader.Close(); /* Return File Size */ _result = _fileInfo; } catch (Exception ex) { //Console.WriteLine(ex.ToString()); _result = ex.Message.ToString(); } finally { /* Resource Cleanup */ ftpStream.Flush(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; } return _result; }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { // Veritabanı Kurulumu - İlk Açılışta if (islem == 0) { functions.dbCreate(); } // Kategori Adı Düzenleme else if (islem == 1) { try { Form1.baglanti.Open(); SQLiteCommand updateCommand = new SQLiteCommand("update kategoriler set kategoriAdi = '" + updateCategory.kategoriAdi + "' where kategoriID = " + updateCategory.kategoriID, Form1.baglanti); updateCommand.ExecuteNonQuery(); updateCategory.sonuc = true; } catch (SQLiteException) { updateCategory.sonuc = false; } finally { Form1.baglanti.Close(); } } // Kategori Silme else if (islem == 2) { try { Form1.baglanti.Open(); SQLiteCommand kategoriSil = new SQLiteCommand("delete from kategoriler where kategoriID = " + seeCategories.kategoriID, Form1.baglanti); kategoriSil.ExecuteNonQuery(); SQLiteCommand urunSil = new SQLiteCommand("delete from urunler where kategoriID = " + seeCategories.kategoriID, Form1.baglanti); urunSil.ExecuteNonQuery(); seeCategories.sonuc = true; } catch (SQLiteException) { seeCategories.sonuc = false; } finally { Form1.baglanti.Close(); } } // Kategori Ekleme else if (islem == 3) { try { Form1.baglanti.Open(); SQLiteCommand catControl = new SQLiteCommand("select kategoriID from kategoriler where kategoriAdi = ?", Form1.baglanti); catControl.Parameters.AddWithValue("kategoriAdi", addCategory.catName); SQLiteDataReader catRead = catControl.ExecuteReader(); if (catRead.Read()) { addCategory.sonuc = 1; } else { try { SQLiteCommand addCat = new SQLiteCommand("insert into kategoriler(kategoriAdi) values(?)", Form1.baglanti); addCat.Parameters.AddWithValue("kategoriAdi", addCategory.catName); addCat.ExecuteNonQuery(); addCategory.sonuc = 2; } catch (Exception) { addCategory.sonuc = 0; } } } catch (SQLiteException) { addCategory.sonuc = 0; } finally { Form1.baglanti.Close(); } } // Ürün Ekleme else if (islem == 4) { try { Form1.baglanti.Open(); SQLiteCommand productControl = new SQLiteCommand("select urunID from urunler where urunAdi = ? and kategoriID = ?", Form1.baglanti); productControl.Parameters.AddRange(new SQLiteParameter[] { new SQLiteParameter("urunAdi", addProduct.urunAdi), new SQLiteParameter("kategoriID", addProduct.kategoriID) }); SQLiteDataReader productRead = productControl.ExecuteReader(); if (productRead.Read()) { addProduct.sonuc = 1; } else { try { SQLiteCommand AddProduct = new SQLiteCommand("insert into urunler(urunAdi, urunFiyati, kategoriID) values('" + addProduct.urunAdi + "', '" + addProduct.fiyat + "', " + addProduct.kategoriID + ")", Form1.baglanti); AddProduct.ExecuteNonQuery(); addProduct.sonuc = 2; } catch (SQLiteException) { addProduct.sonuc = 0; } } } catch (SQLiteException) { addProduct.sonuc = 0; } finally { Form1.baglanti.Close(); } } // Ürün Silme else if (islem == 5) { Form1.baglanti.Open(); try { SQLiteCommand productDelete = new SQLiteCommand("delete from urunler where urunID = " + seeProduct.urunID, Form1.baglanti); productDelete.ExecuteNonQuery(); seeProduct.sonuc = true; } catch (SQLiteException ex) { MessageBox.Show(ex.Message); seeProduct.sonuc = false; } finally { Form1.baglanti.Close(); } } // Ürün Bilgilerini Getirme else if (islem == 6) { Form1.baglanti.Close(); Form1.baglanti.Open(); SQLiteCommand productCommand = new SQLiteCommand("select * from urunler where urunID = " + seeProduct.urunID, Form1.baglanti); SQLiteDataReader productRead = productCommand.ExecuteReader(); productRead.Read(); updateProduct.urunAdi = productRead["urunAdi"].ToString(); updateProduct.urunFiyati = productRead["urunFiyati"].ToString(); Form1.baglanti.Close(); } // Ürün Bilgilerini Güncelleme else if (islem == 7) { try { Form1.baglanti.Close(); Form1.baglanti.Open(); SQLiteCommand productUpdate = new SQLiteCommand("update urunler set urunAdi = '" + updateProduct.urunAdi + "', urunFiyati = '" + updateProduct.urunFiyati + "', kategoriID = " + updateProduct.kategoriID + " where urunID = " + seeProduct.urunID, Form1.baglanti); productUpdate.ExecuteNonQuery(); updateProduct.sonuc = true; } catch (SQLiteException) { updateProduct.sonuc = false; } finally { Form1.baglanti.Close(); } } // Sunucu Bağlantı Denemesi else if (islem == 8) { if (serverSettings.sunucu.StartsWith("ftp")) { FtpWebRequest requestDir = FtpWebRequest.Create(serverSettings.sunucu) as FtpWebRequest; requestDir.Credentials = new NetworkCredential(serverSettings.kullanici, serverSettings.sifre); requestDir.Timeout = 10000; requestDir.Method = WebRequestMethods.Ftp.ListDirectory; try { WebResponse response = requestDir.GetResponse(); serverSettings.sonuc = true; } catch (Exception) { serverSettings.sonuc = false; } } else if (serverSettings.sunucu.StartsWith("http")) { HttpWebRequest requestDir = HttpWebRequest.Create(serverSettings.sunucu) as HttpWebRequest; requestDir.Credentials = new NetworkCredential(serverSettings.kullanici, serverSettings.sifre); requestDir.Timeout = 10000; requestDir.Method = WebRequestMethods.Ftp.ListDirectory; try { WebResponse response = requestDir.GetResponse(); serverSettings.sonuc = true; } catch (Exception) { serverSettings.sonuc = false; } } else { serverSettings.sonuc = false; } } // Dosya Yedekleme else if (islem == 9) { try { DirectoryInfo dii = new DirectoryInfo(makeBackup.yedeklenecekler); string diName = dii.Name; string tarih = DateTime.Now.ToString().Split(' ')[0].Replace('.', '-') + " Gün " + diName + " Yedeği"; string yeniKlasorAdi = makeBackup.yedekKlasor + "\\Yedekler\\" + tarih; if (!Directory.Exists(yeniKlasorAdi)) { Directory.CreateDirectory(yeniKlasorAdi); } string[] klasorler = Directory.GetDirectories(makeBackup.yedeklenecekler, "*.*", SearchOption.AllDirectories); foreach (string klasor in klasorler) { DirectoryInfo di = new DirectoryInfo(klasor); if (!Directory.Exists(yeniKlasorAdi + "\\" + di.Name)) { Directory.CreateDirectory(yeniKlasorAdi + "\\" + di.Name); } } string[] dosyalar = Directory.GetFiles(makeBackup.yedeklenecekler, "*.*", SearchOption.AllDirectories); foreach (string dosya in dosyalar) { FileInfo fi = new FileInfo(dosya); string[] directory = fi.DirectoryName.Split('\\'); string directoryName = directory[directory.Length - 1]; string newName = (makeBackup.yedeklenecekler.ToLower().Contains("siparisler")) ? yeniKlasorAdi + "\\" + fi.Name : yeniKlasorAdi + "\\" + directoryName + "\\" + fi.Name; if (File.Exists(newName)) { File.Delete(newName); } File.Copy(dosya, newName); } if (makeBackup.ziple) { ziple(makeBackup.yedeklenecekler, yeniKlasorAdi + "\\" + diName + ".zip", makeBackup.sifre); } makeBackup.sonuc = true; } catch { makeBackup.sonuc = false; } } // FTP Yedek Yükleme else if (islem == 10) { string dosya = Form1.tempDir + "\\yedek.zip"; ziple(makeBackup.yedeklenecekler, dosya, null); string settingsDoc = Form1.tempDir + "\\Ayarlar\\sunucu.json"; JObject server = JObject.Parse(File.ReadAllText(settingsDoc)); string sunucu = server["server"]["sunucuAdres"].ToString(); string port = server["server"]["port"].ToString(); string kullaniciAdi = server["server"]["kullaniciAdi"].ToString(); string sifre = server["server"]["sifre"].ToString(); if (sunucu.Contains("ftp")) { ftpIstegi = (FtpWebRequest)FtpWebRequest.Create(new Uri(sunucu)); } else if (sunucu.Contains("http")) { ftpIstegi = (HttpWebRequest)HttpWebRequest.Create(new Uri(sunucu)); } ftpIstegi.Credentials = new NetworkCredential(kullaniciAdi, sifre); ftpIstegi.Method = WebRequestMethods.Ftp.UploadFile; FileInfo dosyaBilgisi = new FileInfo(dosya); ftpIstegi.ContentLength = dosyaBilgisi.Length; int bufferUzunlugu = 2048; byte[] buff = new byte[10000000]; int sayi; FileStream stream = dosyaBilgisi.OpenRead(); try { Stream str = ftpIstegi.GetRequestStream(); sayi = stream.Read(buff, 0, bufferUzunlugu); while (sayi != 0) { str.Write(buff, 0, sayi); sayi = stream.Read(buff, 0, bufferUzunlugu); } str.Close(); stream.Close(); File.Delete(dosya); makeBackup.sonuc = true; } catch (Exception) { makeBackup.sonuc = false; } } }
/// <summary> /// Download. /// </summary> /// <param name="uri"></param> /// <param name="useNTLM"></param> /// <returns></returns> private static string Download(System.Uri uri, ICredentials credentials) { if (uri.Scheme.ToLower() == "http") { HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(uri); httpWebRequest.Method = WebRequestMethods.Http.Get; httpWebRequest.Timeout = 3600000; if (credentials != null) { httpWebRequest.Credentials = credentials; } string syndication = null; using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse()) { Stream s = httpWebResponse.GetResponseStream(); MemoryStream ms = new MemoryStream(); byte[] b = new byte[1]; int count = 0; do { count = s.Read(b, 0, 1); if (count != 0) { ms.Write(b, 0, 1); } } while (count != 0); ms.Seek(0, SeekOrigin.Begin); byte[] buffer = new byte[ms.Length]; ms.Read(buffer, 0, Convert.ToInt32(ms.Length)); ms.Seek(0, SeekOrigin.Begin); Encoding srcEncoding = Encoding.GetEncoding(GetCharacterSet(httpWebResponse.CharacterSet, httpWebResponse.ContentType)); using (StreamReader sr = new StreamReader(ms, srcEncoding)) { syndication = sr.ReadToEnd(); }// using // If we did not have a proper encoding recode it if (string.IsNullOrEmpty(httpWebResponse.CharacterSet) && IsXmlContentType(httpWebResponse.ContentType)) { ms = new MemoryStream(buffer); ms.Seek(0, SeekOrigin.Begin); syndication = ConvertToEncoding(syndication, ms); }// if } return(syndication); } else if (uri.Scheme.ToLower() == "ftp") { FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(uri); ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpWebRequest.Timeout = 3600000; if (credentials != null) { ftpWebRequest.Credentials = credentials; } using (FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse()) { Stream s = ftpWebResponse.GetResponseStream(); string filename = Path.GetTempFileName(); using (FileStream fs = new FileStream(filename, FileMode.Create)) { byte[] buffer = new byte[2048]; int len = 0; while ((len = s.Read(buffer, 0, 2048)) > 0) { fs.Write(buffer, 0, len); } } XmlDocument xd = new XmlDocument(); xd.Load(filename); return(xd.OuterXml); } } throw new ArgumentException(Syndication.URI_FORMAT_UNSUPPORTED_OR_INVALID, "uri"); }
public async Task <List <ListingData> > ListDirectory(string userName, string password, string ftpServer) { return(await Task.Run(() => { List <ListingData> files = new List <ListingData>(); try { //Create FTP request FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpServer); //req.Method = WebRequestMethods.Ftp.ListDirectory; //req.Method = WebRequestMethods.Ftp.GetDateTimestamp; req.Method = WebRequestMethods.Ftp.ListDirectoryDetails; req.Credentials = new NetworkCredential(userName, password); req.UsePassive = true; req.UseBinary = true; //req.KeepAlive = false; using (FtpWebResponse response = (FtpWebResponse)req.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { string pattern = @"^([\w-]+)\s+(\d+)\s+(\w+)\s+(\w+)\s+(\d+)\s+" + @"(\w+\s+\d+\s+\d+|\w+\s+\d+\s+\d+:\d+)\s+(.+)$"; Regex regex = new Regex(pattern); IFormatProvider culture = CultureInfo.GetCultureInfo("en-us"); string[] hourMinFormats = new[] { "MMM dd HH:mm", "MMM dd H:mm", "MMM d HH:mm", "MMM d H:mm" }; string[] yearFormats = new[] { "MMM dd yyyy", "MMM d yyyy" }; while (!reader.EndOfStream) { string line = reader.ReadLine(); Match match = regex.Match(line); string permissions = match.Groups[1].Value; int inode = int.Parse(match.Groups[2].Value, culture); string owner = match.Groups[3].Value; string group = match.Groups[4].Value; long size = long.Parse(match.Groups[5].Value, culture); DateTime?modified; string s = Regex.Replace(match.Groups[6].Value, @"\s+", " "); if (s.IndexOf(':') >= 0) { modified = DateTime.ParseExact(s, hourMinFormats, culture, DateTimeStyles.None); } else { modified = DateTime.ParseExact(s, yearFormats, culture, DateTimeStyles.None); } string name = match.Groups[7].Value; var data = new ListingData(name, modified); files.Add(data); } //Clean-up reader.Close(); responseStream.Close(); //redundant response.Close(); } } } return files; } catch (Exception) { return null; } })); }
public static string DownloadFile(string sourceFileUrl, string destinationFilePath, string username = FTP.UserName, string password = FTP.Password) { string output; // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(sourceFileUrl); //Specify the method of transaction request.Method = WebRequestMethods.Ftp.DownloadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential(username, password); //Indicate Binary so that any file type can be downloaded request.UseBinary = true; request.KeepAlive = false; try { //Create an instance of a Response object using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { //Request a Response from the server using (Stream stream = response.GetResponseStream()) { //Build a variable to hold the data using a size of 1Mb or 1024 bytes byte[] buffer = new byte[1024]; //1 Mb chucks //Establish a file stream to collect data from the response using (FileStream fs = new FileStream(destinationFilePath, FileMode.Create)) { //Read data from the stream at the rate of the size of the buffer int bytesRead = stream.Read(buffer, 0, buffer.Length); //Loop until the stream data is complete while (bytesRead > 0) { //Write the data to the file fs.Write(buffer, 0, bytesRead); //Read data from the stream at the rate of the size of the buffer bytesRead = stream.Read(buffer, 0, buffer.Length); } //Close the StreamReader fs.Close(); } //Close the Stream stream.Close(); } //Close the FtpWebResponse response.Close(); //Output the results to the return string output = $"Download Complete, status {response.StatusDescription}"; } } catch (WebException e) { FtpWebResponse response = (FtpWebResponse)e.Response; //Something went wrong with the Web Request output = e.Message + $"\n Exited with status code {response.StatusCode}"; } catch (Exception e) { //Something went wrong output = e.Message; } //Return the output of the Responce return(output); }
private void btnGuardar_Click(object sender, EventArgs e) { try { if (txtNombre.Text != "") { this.Enabled = false; MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(); builder.Server = "31.170.166.58"; builder.UserID = "u215283317_pb"; builder.Password = "******"; builder.Database = "u215283317_pb"; MySqlConnection conn = new MySqlConnection(builder.ToString()); MySqlCommand cmd = conn.CreateCommand(); string nombreServer = txtNombre.Text + "_" + DateTime.Now.ToString().Replace(' ', '_'); nombreServer = nombreServer.Replace('/', '_'); string tabla = ""; if (checkBox1.Checked) { tabla = "archivostrabajadores (trabajador_id, "; } else { tabla = "archivos (cliente_id, "; } cmd.CommandText = "INSERT INTO " + tabla + "nombre, nombre_servidor, descripcion, observaciones, extension, visible) value ('" + cbClientes.SelectedItem.ToString().Split(',')[0] + "', '" + txtNombre.Text + ".pdf', '" + nombreServer + ".pdf', '" + txtDescripcion.Text + "', '" + txtObservaciones.Text + "', '.pdf', 'si')"; conn.Open(); cmd.ExecuteNonQuery(); guardarPDF(txtNombre.Text); FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.abogadosynotariosroldan.com/" + nombreServer + ".pdf"); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential("u215283317.remoto", "abogadosroldan"); StreamReader sourceStream = new StreamReader(carpeta + txtNombre.Text + ".pdf"); 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(); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription); response.Close(); MessageBox.Show("Archivo cargado con éxito", "Operación exitosa", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.Close(); } else { MessageBox.Show("Debe llenar el campo Nombre para continuar", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { this.Enabled = true; MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); } }
/// <summary> /// 检索服务器文件 /// </summary> /// <param name="targetDir"></param> /// <param name="pattern"></param> /// <returns></returns> public List <FtpFile> RetrieveServerFiles(string targetDir, string pattern) { List <FtpFile> result = new List <FtpFile>(); try { string url = "ftp://" + ip + "/" + targetDir + "/" + pattern; FtpWebRequest ftp = GetRequest(url); ftp.Method = WebRequestMethods.Ftp.ListDirectory; ftp.UsePassive = true; ftp.UseBinary = true; string responseStr = string.Empty; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse()) { long size = response.ContentLength; using (Stream dataStream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(dataStream, Encoding.UTF8)) { responseStr = sr.ReadToEnd(); sr.Close(); } dataStream.Close(); } response.Close(); } responseStr = responseStr.Replace("\r\n", "\r").TrimEnd('\r'); responseStr = responseStr.Replace("\n", "\r"); if (!string.IsNullOrEmpty(responseStr)) { var strs = responseStr.Split('\r'); if (strs != null && strs.Length > 0) { foreach (string str in strs) { FtpFile ftpFile = new FtpFile(); ftpFile.Name = Path.GetFileNameWithoutExtension(str); ftpFile.FullName = str; ftpFile.Path = "ftp://" + ip + "/" + targetDir + "/" + str; #region 获取ftp文件大小 long fileSize = 0; //文件大小 FtpWebRequest reqFtp = GetRequest(ftpFile.Path); reqFtp.UseBinary = true; reqFtp.Method = WebRequestMethods.Ftp.GetFileSize; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse()) { fileSize = response.ContentLength; response.Close(); } #endregion ftpFile.Size = fileSize; result.Add(ftpFile); } } } } catch (Exception ex) { LogHelper.WriteError(ex); } return(result); }
public static string CreateFileFTP(string basePath, string userName, string password, bool ftps, string fileName, string dataString, bool createDirectory, string testFile = "") { FtpWebResponse response = null; string remoteDirectoy = basePath + Guid.NewGuid(); string path = remoteDirectoy + "/" + fileName; try { if (createDirectory) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(remoteDirectoy); request.UseBinary = true; request.KeepAlive = false; request.EnableSsl = ftps; if (userName != string.Empty) { request.Credentials = new NetworkCredential(userName, password); } request.Method = WebRequestMethods.Ftp.MakeDirectory; request.GetResponse(); request = (FtpWebRequest)WebRequest.Create(path); request.UseBinary = true; request.KeepAlive = false; request.EnableSsl = ftps; if (userName != string.Empty) { request.Credentials = new NetworkCredential(userName, password); } request.Method = WebRequestMethods.Ftp.UploadFile; byte[] data; if (string.IsNullOrEmpty(testFile)) { data = Encoding.UTF8.GetBytes(dataString); } else { using (var fs = new FileStream(testFile, FileMode.Open, FileAccess.Read)) { var br = new BinaryReader(fs); long numBytes = new FileInfo(testFile).Length; data = br.ReadBytes((int)numBytes); } } request.ContentLength = data.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(data, 0, Convert.ToInt32(data.Length)); requestStream.Close(); response = (FtpWebResponse)request.GetResponse(); if (response.StatusCode != FtpStatusCode.FileActionOK && response.StatusCode != FtpStatusCode.ClosingData) { throw new Exception("File was not created"); } } } finally { if (response != null) { response.Close(); } } return(path); }
private void playlistadd() { int thumbnailwidth = 150; int thumbnailheight = 150; try { #region add records in the playlist table for the new playlist UInt32 newaddedplaylistid = user.addplaylist(nametxt.Text, new FileInfo(thumbnametxt.Text).Name, descriptiontxt.Text); if (newaddedplaylistid == 0) { throw new Exception(); } #endregion try { #region creating folders for the playlist on the remote server //creating playlist folder string createpath = user.ftpurl + "user_" + user.userid + "/playlist_" + newaddedplaylistid; FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(createpath); request.Credentials = new NetworkCredential(user.ftpusername, user.ftppassword); request.KeepAlive = true; request.Method = WebRequestMethods.Ftp.MakeDirectory; request.GetResponse(); //creating audios folder in the playlist folder createpath = user.ftpurl + "user_" + user.userid + "/playlist_" + newaddedplaylistid + "/audios"; request = (FtpWebRequest)FtpWebRequest.Create(createpath); request.Credentials = new NetworkCredential(user.ftpusername, user.ftppassword); request.KeepAlive = true; request.Method = WebRequestMethods.Ftp.MakeDirectory; request.GetResponse(); #endregion #region uploading thumbnail of the playlist to the remote server try { int ChunkSize = 4096, NumRetries = 0, MaxRetries = 20; byte[] Buffer = new byte[ChunkSize]; string onlythumbname = new FileInfo(thumbnametxt.Text).Name; Image thumbimg = Image.FromFile(thumbnametxt.Text).GetThumbnailImage(thumbnailwidth, thumbnailheight, thumbnailcreationfailedcallback, IntPtr.Zero); MemoryStream thumbimgstream = new MemoryStream(); thumbimg.Save(thumbimgstream, System.Drawing.Imaging.ImageFormat.Jpeg); thumbimgstream.Position = 0; string UploadPath = user.ftpurl + "user_" + user.userid + "/playlist_" + newaddedplaylistid + "/" + onlythumbname; request = (FtpWebRequest)WebRequest.Create(UploadPath); request.Method = WebRequestMethods.Ftp.UploadFile; request.KeepAlive = true; request.Credentials = new NetworkCredential(user.ftpusername, user.ftppassword); using (Stream requestStream = request.GetRequestStream()) { using (thumbimgstream) { int BytesRead = thumbimgstream.Read(Buffer, 0, ChunkSize); // read the first chunk in the buffer // send the chunks to the web service one by one, until FileStream.Read() returns 0, meaning the entire file has been read. while (BytesRead > 0) { try { requestStream.Write(Buffer, 0, BytesRead); } catch { if (NumRetries++ < MaxRetries) { // rewind the imagememeorystream and keep trying thumbimgstream.Position -= BytesRead; } else { throw new Exception(); } } BytesRead = thumbimgstream.Read(Buffer, 0, ChunkSize); // read the next chunk (if it exists) into the buffer. the while loop will terminate if there is nothing left to read } } } } catch (Exception) { //thumbnail could not be uploaded so remote folders have to be deleted #region deleting folder that were created for the playlist string deletepath = user.ftpurl + "user_" + user.userid + "/playlist_" + newaddedplaylistid; new DeleteFTPDirectory().DeleteDirectoryHierarcy(deletepath); #endregion throw new Exception(); } #endregion } catch (Exception) { #region deleting playlist record from the database //If folder could not be created or thumbnail could not be created remove the playlist record from the playlist table in the database user.deleteplaylist(newaddedplaylistid); throw new Exception(); #endregion } } catch (Exception) { MessageBox.Show("The playlist could not be added"); return; } MessageBox.Show("The playlist has been added"); //this.Close(); }
public DowloadFileStream(FtpWebRequest request) { request.Method = WebRequestMethods.Ftp.DownloadFile; ftpStream = request.GetResponse().GetResponseStream(); }
/// <summary> /// 列出文件目录详细信息 /// </summary> /// <param name="FolderName">目录名</param> /// <returns>文件信息列表</returns> public FtpFileInfo[] ListDirectoryDetails(string FolderName) { try { if (FolderName == null) { FolderName = ""; } if (this.Url.Trim() != "") { string str = Url + "/" + FolderName.Trim(); Uri uri = new Uri(str); List <FtpFileInfo> list = new List <FtpFileInfo>(); FtpWebRequest listRequest = (FtpWebRequest)FtpWebRequest.Create(uri); listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; listRequest.Timeout = TimeOut; if (account.UserName.Trim() != "") { listRequest.Credentials = account; } FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse(); Stream responseStream = listResponse.GetResponseStream(); StreamReader readStream = new StreamReader(responseStream, System.Text.Encoding.Default); while (readStream.Peek() >= 0) { str = readStream.ReadLine(); FtpFileInfo temp = new FtpFileInfo(); if (str.Substring(0, 1).ToUpper().Trim() == "D") { temp.IsDirectory = true; } else { temp.IsDirectory = false; } temp.FileName = str.Substring(55).Trim(); long ints = 0; long.TryParse(str.Substring(29, 12).Trim(), out ints); temp.Size = ints; DateTime DT; DateTime.TryParse(str.Substring(42, 12).Trim(), out DT); temp.EditDate = DT; temp.Role = str.Substring(1, 9).Trim(); list.Add(temp); } listResponse.Close(); listResponse = null; listRequest = null; if (list.Count > 0) { FtpFileInfo[] res = new FtpFileInfo[list.Count]; list.CopyTo(res); return(res); } } return(null); } catch (Exception ex) { ErrMsg = ex.Message; return(null); } }
public HttpResponseMessage Post(int id, string bandera) { HttpResponseMessage result = null; var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { var docfiles = new List <string>(); var NombreArchivo = ""; foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; NombreArchivo = postedFile.FileName; var filePath = HttpContext.Current.Server.MapPath("~/Areas/" + postedFile.FileName); postedFile.SaveAs(filePath); docfiles.Add(filePath); try { try { FtpWebRequest reqFTP = null; Stream ftpStream = null; reqFTP = (FtpWebRequest)FtpWebRequest.Create("ftp://65.99.252.110/httpdocs/assets/images/prestamos/" + id); reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential("steujedo", "Sindicato#1586"); FtpWebResponse response2 = (FtpWebResponse)reqFTP.GetResponse(); ftpStream = response2.GetResponseStream(); ftpStream.Close(); response2.Close(); } catch (Exception ex) { //directory already exist I know that is weak but there is no way to check if a folder exist on ftp... } //Call A FileUpload Method of FTP Request Object FtpWebRequest reqObj = (FtpWebRequest)WebRequest.Create("ftp://65.99.252.110/httpdocs/assets/images/prestamos/" + id + "/" + postedFile.FileName); reqObj.Method = WebRequestMethods.Ftp.UploadFile; //If you want to access Resourse Protected,give UserName and PWD reqObj.Credentials = new NetworkCredential("steujedo", "Sindicato#1586"); // Copy the contents of the file to the byte array. byte[] fileContents = File.ReadAllBytes(filePath); 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(); response.Close(); File.Delete(filePath); } catch (Exception Ex) { throw Ex; } } try { using (steujedo_sindicatoEntities db = new steujedo_sindicatoEntities()) { Caja_Ahorro caja = db.Caja_Ahorro.Where(p => p.pre_id.Equals(id)).First(); if (caja == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Prestamo no encontrada")); } else { if (bandera.Equals("RECIBO")) { caja.pre_recibo = "assets/images/prestamos/" + id + "/" + NombreArchivo; } if (bandera.Equals("INE")) { caja.pre_ine = "assets/images/prestamos/" + id + "/" + NombreArchivo; } db.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK)); } } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } //result = Request.CreateResponse(HttpStatusCode.Created, docfiles); } else { result = Request.CreateResponse(HttpStatusCode.BadRequest); } return(result); }
/// <summary> /// 下载文件,带断点下载 /// </summary> /// <param name="FolderName">目录名</param> /// <param name="FileName">文件名</param> /// <param name="LocalPath">本地路径</param> /// <param name="LocalFile">本地文件名,为空则用FileName</param> /// <param name="ReDownLoad">重新下载</param> /// <param name="Checked">是否对比大小</param> /// <param name="BufferSize">缓存大小</param> /// <returns>执行结果</returns> public bool DownLoadFile(string FolderName, string FileName, string LocalPath, string LocalFile = "", bool ReDownLoad = false, bool Checked = false, int BufferSize = 4096) { try { if (FolderName == null) { FolderName = ""; } if (FileName == null || LocalPath == null) { ErrMsg = "REF unvalid"; return(false); } else if (FileName.Trim() == "" || LocalPath.Trim() == "") { ErrMsg = "REF unvalid"; return(false); } else { DirectoryInfo di = new DirectoryInfo(LocalPath); if (!di.Exists) { di.Create(); } FileInfo fi; if (LocalFile.Trim() != "") { fi = new FileInfo(LocalPath + "\\" + LocalFile); } else { fi = new FileInfo(LocalPath + "\\" + FileName); } if (this.Url.Trim() != "") { string str = Url + "/" + FolderName.Trim(); str = str + "/" + FileName; Uri uri = new Uri(str); FtpWebRequest listRequest = (FtpWebRequest)FtpWebRequest.Create(uri); listRequest.Method = WebRequestMethods.Ftp.DownloadFile; listRequest.Timeout = TimeOut; if (account.UserName.Trim() != "") { listRequest.Credentials = account; } listRequest.KeepAlive = true; listRequest.UseBinary = true; listRequest.UsePassive = true; System.IO.FileStream fs; if (fi.Exists) { if (ReDownLoad) { fi.Delete(); fs = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Create, System.IO.FileAccess.Write); } else { listRequest.ContentOffset = fi.Length; fs = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Append, System.IO.FileAccess.Write); } } else { fs = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Create, System.IO.FileAccess.Write); } bool resdo = false; try { FtpWebResponse ftpRes = (FtpWebResponse)listRequest.GetResponse(); System.IO.Stream resStrm = ftpRes.GetResponseStream(); byte[] buffer = new byte[BufferSize]; while (true) { int readSize = resStrm.Read(buffer, 0, buffer.Length); if (readSize == 0) { break; } fs.Write(buffer, 0, readSize); } resStrm.Close(); ftpRes.Close(); ftpRes = null; resdo = true; } catch (Exception exx) { ErrMsg = exx.Message; resdo = false; } finally { fs.Close(); listRequest = null; } if (Checked) { listRequest = (FtpWebRequest)FtpWebRequest.Create(uri); listRequest.Method = WebRequestMethods.Ftp.GetFileSize; listRequest.Timeout = TimeOut; listRequest.KeepAlive = true; listRequest.UseBinary = false; if (account.UserName.Trim() != "") { listRequest.Credentials = account; } FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse(); long upsize = 0; try { string[] res = listResponse.StatusDescription.Replace("\r\n", "").Split(' '); upsize = long.Parse(res[1]); } catch { } listResponse.Close(); listResponse = null; listRequest.Abort(); if (LocalFile.Trim() != "") { fi = new FileInfo(LocalPath + "\\" + LocalFile); } else { fi = new FileInfo(LocalPath + "\\" + FileName); } if (fi.Length == upsize) { return(true); } else { return(false); } } else { return(resdo); } } return(false); } } catch (Exception ex) { ErrMsg = ex.Message; return(false); } }
//ftp://aktheknight.co.uk/public_html/stuff/ private void btnUpload_Click(object sender, EventArgs e) { Debug.Print("Kappa"); Stream myStream = null; OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = "c:\\"; openFileDialog1.RestoreDirectory = true; openFileDialog1.Multiselect = false; if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { if ((myStream = openFileDialog1.OpenFile()) != null) { using (myStream) { // Insert code to read the stream here label1.Text = "DONE"; // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest) WebRequest.Create(Properties.Settings.Default["FTPAddress"].ToString() + "/" + openFileDialog1.SafeFileName); request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential(Properties.Settings.Default["FTPUsername"].ToString(), Properties.Settings.Default["FTPPassword"].ToString()); // Copy the contents of the file to the request stream. StreamReader sourceStream = new StreamReader(openFileDialog1.OpenFile()); 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(); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); label1.Text = String.Format("Upload File Complete, status {0}", response.StatusDescription); response.Close(); Clipboard.SetText(Properties.Settings.Default["FTPLink"] + openFileDialog1.SafeFileName); Hide(); } } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } }
/* Create a New Directory on the FTP Server */ public void createDirectory(string newDirectory) { try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + newDirectory); /* 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.MakeDirectory; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Resource Cleanup */ ftpResponse.Close(); ftpRequest = null; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return; }
/* Download File */ public void download(string remoteFile, string localFile, Action <int, bool> _BytesDownloaded = null, int _ReportBytesDownloadedEvery = 1024 * 10) { 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.DownloadFile; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); /* Get the FTP Server's Response Stream */ ftpStream = ftpResponse.GetResponseStream(); /* Open a File Stream to Write the Downloaded File */ FileStream localFileStream = new FileStream(localFile, FileMode.Create); /* Buffer for the Downloaded Data */ byte[] byteBuffer = new byte[bufferSize]; int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); /* Download the File by Writing the Buffered Data Until the Transfer is Complete */ int totalDownloaded = 0; int bytesUntilReport = 0; try { while (bytesRead > 0) { if (_BytesDownloaded != null) { totalDownloaded += bytesRead; bytesUntilReport += bytesRead; if (bytesUntilReport > _ReportBytesDownloadedEvery) { bytesUntilReport -= _ReportBytesDownloadedEvery; try { _BytesDownloaded(totalDownloaded, false); } catch (Exception) {} } } localFileStream.Write(byteBuffer, 0, bytesRead); bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } /* Resource Cleanup */ localFileStream.Close(); ftpStream.Close(); ftpResponse.Close(); ftpRequest = null; if (_BytesDownloaded != null) { _BytesDownloaded(totalDownloaded, true); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return; }
private void ReadFileFromFTPTrasladoGuia(List <string> files) { foreach (string file in files) { if (file != null && file.Contains(".txt")) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ruta_ftp_inventario + file); request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential("ftpwms", "wmsapia"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); string contents = reader.ReadToEnd(); Transaction transaction = Common.InitTransaction(); List <RowItem> itemlist = new List <RowItem>(); string line = ""; using (StringReader strReader = new StringReader(contents)) { int contador = 0; while ((line = strReader.ReadLine()) != null) { if (contador > 0) { RowItem item = new RowItem(); item.v01 = line.Split('|')[0]; item.v02 = line.Split('|')[1]; item.v03 = line.Split('|')[2]; item.v04 = line.Split('|')[3]; item.v05 = line.Split('|')[4]; item.v06 = line.Split('|')[5]; itemlist.Add(item); } contador++; } } reader.Close(); reader.Dispose(); response.Close(); RowItemCollection itemcollection = new RowItemCollection(); var itemlistOrder = (from row in itemlist orderby row.v02, row.v06 select row).ToList(); for (int i = 0; i < itemlistOrder.Count(); i++) { RowItem item = new RowItem(); item.v01 = itemlistOrder.ToList()[i].v01; item.v02 = itemlistOrder.ToList()[i].v02; item.v03 = itemlistOrder.ToList()[i].v03; item.v04 = itemlistOrder.ToList()[i].v04; item.v05 = Convert.ToInt32(Math.Abs(Convert.ToDecimal(itemlistOrder.ToList()[i].v05))).ToString(); item.v06 = itemlistOrder.ToList()[i].v06; i++; item.v07 = itemlistOrder.ToList()[i].v06; itemcollection.rows.Add(item); } if (!Directory.Exists(@"C:\Data")) { Directory.CreateDirectory(@"C:\Data"); } if (!Directory.Exists(@"C:\Data\temp")) { Directory.CreateDirectory(@"C:\Data\temp"); } string name = string.Format(@"{0}_{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), file); string temp = string.Format(@"C:\Data\temp\{0}", name); //File.Create(temp); List <string> lines = new List <string>(); foreach (var row in itemcollection.rows) { lines.Add(string.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}", row.v01, row.v02, row.v03, row.v04, row.v05, row.v06, row.v07)); } bool result = new blTareo().ProcesarTrasladoGuia(itemcollection, out transaction); lines.Add(transaction.type.ToString() + ":" + transaction.message); File.WriteAllLines(temp, lines.ToArray()); if (result) { UploadFTP(temp, ruta_ftp_inventario + "success/", "ftpwms", "wmsapia"); } else { UploadFTP(temp, ruta_ftp_inventario + "failed/", "ftpwms", "wmsapia"); } //Eliminar fichero request = (FtpWebRequest)WebRequest.Create(ruta_ftp_inventario + file); request.Method = WebRequestMethods.Ftp.DeleteFile; request.Credentials = new NetworkCredential("ftpwms", "wmsapia"); response = (FtpWebResponse)request.GetResponse(); response.Close(); File.Delete(temp); } } }
/// <summary> /// 更改目录或文件名 /// </summary> /// <param name="currentName">当前名称</param> /// <param name="newName">修改后新名称</param> public void ReName(string currentName, string newName) { request = PrivateAction.OpenRequest(this.ftpUserID, this.ftpPassword, this.request, newUri(ftpURI + currentName), WebRequestMethods.Ftp.Rename); request.RenameTo = newName; response = (FtpWebResponse)request.GetResponse(); }
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; }
/* Rename File */ public string rename(string currentFileNameAndPath, string newFileName) { string _result = null; try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + currentFileNameAndPath); /* 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.Rename; /* Rename the File */ ftpRequest.RenameTo = newFileName; /* Establish Return Communication with the FTP Server */ ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); } catch (Exception ex) { //Console.WriteLine(ex.ToString()); _result = ex.Message.ToString(); } finally { /* Resource Cleanup */ ftpResponse.Close(); ftpRequest = null; } return _result; }