Search Results

Search found 23 results on 1 pages for 'ftpwebresponse'.

Page 1/1 | 1 

  • FtpWebResponse and StreamReader - specifying an offset

    - by AJ
    Hi, I am using the FtpWebRequest / FtpWebResponse objects in C# to download files from a server - so far, so good. I create a StreamReader object from the response stream and use a StreamWriter to create a local file. Now, the file I am reading happens to be in a very simple 'archive' format - there is a small TOC at the start of the file followed by the actual file data. I can therefore read the TOC and get a file offset and size of the data I want to download. My question is: Supposing the offset is 1024. I would use StreamReader.Read(buffer, 1024, length), but will .NET and the FTP protocol actually allow me to skip bytes 0-1023, or does the reader still go through the (relatively) slow process of downloading and discarding the bytes I don't need? This may make the difference between whether I want to use a single archive file, or a TOC file with the data files stored separately. As a bit of a secondary question, would my mileage vary using the Http classes instead of Ftp? Cheers, Adam

    Read the article

  • Status Code from FTPWebRequest GetResponse method

    - by nick
    This is slightly tricky. I am uploading files to FTP asynchronously. After uploading each file I am checking the status of the upload operation for that file. This can be done with StatusCode property of the FtpWebResponse object for that request. The code snippet is as give below. System.IO.FileStream fs = System.IO.File.Open(fileName, System.IO.FileMode.Open); while ((iWork = fs.Read(buf, 0, buf.Length)) > 0) requestStream.Write(buf, 0, iWork); requestStream.Close(); FtpWebResponse wrRet = ((FtpWebResponse)state.Request.GetResponse()); There are about 37 StatusCode values as per msdn. I am unaware as to which of these status code values will assure that the file is uploaded successfully. Some of them I used in my code to check for success are : wrRet.StatusCode == FtpStatusCode.CommandOK wrRet.StatusCode == FtpStatusCode.ClosingData wrRet.StatusCode == FtpStatusCode.ClosingControl wrRet.StatusCode == FtpStatusCode.ConnectionClosed wrRet.StatusCode == FtpStatusCode.FileActionOK wrRet.StatusCode == FtpStatusCode.FileStatus But I am unaware of the rest. I need to be sure about these codes because based on the failure or success of the upload operation I have other dependant operations to be carried out. A wrong condition can affect the remaining code. Another thought that crossed my mind was to simply put the above code into a try..catch and not depend on these status codes. With this I would not be depending on the status codes and assuming that any failure will always be directed to the catch block. Kindly let me know if this is the right way. Thanks in advance.

    Read the article

  • FtpWebRequest Download File

    - by pm_2
    The following code is intended to retrieve a file via FTP. However, I'm getting an error with it. serverPath = "ftp://x.x.x.x/tmp/myfile.txt"; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath); request.KeepAlive = true; request.UsePassive = true; request.UseBinary = true; request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(username, password); // Read the file from the server & write to destination using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) // Error here using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream)) using (StreamWriter destination = new StreamWriter(destinationFile)) { destination.Write(reader.ReadToEnd()); destination.Flush(); } The error is: The remote server returned an error: (550) File unavailable (e.g., file not found, no access) The file definately does exist on the remote machine and I am able to perform this ftp manually (i.e. I have permissions). Can anyone tell me why I might be getting this error?

    Read the article

  • C# How to check if an FTP Directory Exists

    - by Billy Logan
    Hello Everyone, Looking for the best way to check for a given directory via FTP. currently i have the following code: private bool FtpDirectoryExists(string directory, string username, string password) { try { var request = (FtpWebRequest)WebRequest.Create(directory); request.Credentials = new NetworkCredential(username, password); request.Method = WebRequestMethods.Ftp.GetDateTimestamp; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); } catch (WebException ex) { FtpWebResponse response = (FtpWebResponse)ex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) return false; else return true; } return true; } This returns false whether the directory is there or not. Can someone point me in the right direction. Thanks in advance, Billy

    Read the article

  • How can I combine my FTP queries? [migrated]

    - by ryansworld10
    My program has several times where it queries an FTP server to read and upload information. How can I combine all these into one FTP class to handle everything? private static void UploadToFTP(string[] FTPSettings) { try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPSettings[0]); request.Method = WebRequestMethods.Ftp.MakeDirectory; request.Credentials = new NetworkCredential(FTPSettings[1], FTPSettings[2]); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); } catch { } try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPSettings[0] + Path.GetFileName(file)); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(FTPSettings[1], FTPSettings[2]); StreamReader source = new StreamReader(file); byte[] fileContents = Encoding.UTF8.GetBytes(source.ReadToEnd()); source.Close(); request.ContentLength = fileContents.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); response.Close(); RegenLog(); } catch (Exception e) { File.AppendAllText(file, string.Format("{0}{0}Upload Failed - ({2}) - {1}{0}", nl, System.DateTime.Now, e.Message.ToString())); } } private static void CheckBlacklist(string[] FTPSettings) { try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPSettings[0] + "blacklist.txt"); request.Credentials = new NetworkCredential(FTPSettings[1], FTPSettings[2]); using (WebResponse response = request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { using (TextReader reader = new StreamReader(stream)) { string blacklist = reader.ReadToEnd(); if (blacklist.Contains(Environment.UserName)) { File.AppendAllText(file, string.Format("{0}{0}Logger terminated - ({2}) - {1}{0}", nl, System.DateTime.Now, "Blacklisted")); uninstall = true; } } } } } catch (Exception e) { File.AppendAllText(file, string.Format("{0}{0}FTP Error - ({2}) - {1}{0}", nl, System.DateTime.Now, e.Message.ToString())); } } private static void CheckUpdate(string[] FTPSettings) { try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPSettings[0] + "update.txt"); request.Credentials = new NetworkCredential(FTPSettings[1], FTPSettings[2]); using (WebResponse response = request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { using (TextReader reader = new StreamReader(stream)) { string newVersion = reader.ReadToEnd(); if (newVersion != version) { update = true; } } } } } catch (Exception e) { File.AppendAllText(file, string.Format("{0}{0}FTP Error - ({2}) - {1}{0}", nl, System.DateTime.Now, e.Message.ToString())); } } I know my code is also a bit inconsistent and messy, however this is my first time working with FTP in C#. Please give any advice you have!

    Read the article

  • FTP Upload ftpWebRequest Proxy

    - by Rodney Vinyard
    Searchable:   FTP Upload ftpWebRequest Proxy FTP command is not supported when using HTTP proxy     In the article below I will cover 2 topics   1.       C# & Windows Command-Line FTP Upload with No Proxy Server   2.       C# & Windows Command-Line FTP Upload with Proxy Server   Not covered here: Secure FTP / SFTP   Sample Attributes: ·         UploadFilePath = “\\servername\folder\file.name” ·         Proxy Server = “ftp://proxy.server/” ·         FTP Target Server = ftp.target.com ·         FTP User = “User” ·         FTP Password = “Password” with No Proxy Server ·         Windows Command-Line > ftp ftp.target.com > ftp User: User > ftp Password: Password > ftp put \\servername\folder\file.name > ftp dir           (result: file.name listed) > ftp del file.name > ftp dir           (result: file.name deleted) > ftp quit   ·         C#   //----------------- //Start FTP via _TargetFtpProxy //----------------- string relPath = Path.GetFileName(\\servername\folder\file.name);   //result: relPath = “file.name”   FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create("ftp.target.com/file.name); ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;   //----------------- //user - password //----------------- ftpWebRequest.Credentials = new NetworkCredential("user, "password");   //----------------- // set proxy = null! //----------------- ftpWebRequest.Proxy = null;   //----------------- // Copy the contents of the file to the request stream. //----------------- StreamReader sourceStream = new StreamReader(“\\servername\folder\file.name”);   byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); ftpWebRequest.ContentLength = fileContents.Length;     //----------------- // transer the stream stream. //----------------- Stream requestStream = ftpWebRequest.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close();   //----------------- // Look at the response results //----------------- FtpWebResponse response = (FtpWebResponse)ftpWebRequest.GetResponse();   Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);   with Proxy Server ·         Windows Command-Line > ftp proxy.server > ftp User: [email protected] > ftp Password: Password > ftp put \\servername\folder\file.name > ftp dir           (result: file.name listed) > ftp del file.name > ftp dir           (result: file.name deleted) > ftp quit   ·         C#   //----------------- //Start FTP via _TargetFtpProxy //----------------- string relPath = Path.GetFileName(\\servername\folder\file.name);   //result: relPath = “file.name”   FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create("ftp://proxy.server/" + relPath); ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;   //----------------- //user - password //----------------- ftpWebRequest.Credentials = new NetworkCredential("[email protected], "password");   //----------------- // set proxy = null! //----------------- ftpWebRequest.Proxy = null;   //----------------- // Copy the contents of the file to the request stream. //----------------- StreamReader sourceStream = new StreamReader(“\\servername\folder\file.name”);   byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); ftpWebRequest.ContentLength = fileContents.Length;     //----------------- // transer the stream stream. //----------------- Stream requestStream = ftpWebRequest.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close();   //----------------- // Look at the response results //----------------- FtpWebResponse response = (FtpWebResponse)ftpWebRequest.GetResponse();   Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

    Read the article

  • 550 Error When I try to get the size of a file on an FTP

    - by Eric
    I'm trying to use an FtpWebRequest to get the size of a file on a company FTP. Yet whenever I try to get the response an exception is thrown. See the error details in the catch block in the code below. string uri = "ftp://ftp.domain.com/folder/folder/file.xxx"; FtpWebRequest sizeReq = (FtpWebRequest)WebRequest.Create(uri); sizeReq.Method = WebRequestMethods.Ftp.GetFileSize; sizeReq.Credentials = cred; sizeReq.UsePassive = proj.ServerConfig.UsePassive; //true sizeReq.UseBinary = proj.ServerConfig.UseBinary; //true sizeReq.KeepAlive = proj.ServerConfig.KeepAlive; //false long size; try { //Exception thrown here when I try to get the response using (FtpWebResponse fileSizeResponse = (FtpWebResponse)sizeReq.GetResponse()) { size = fileSizeResponse.ContentLength; } } catch(WebException exp) { FtpWebResponse resp = (FtpWebResponse)exp.Response; MessageBox.Show(exp.Message); // "The remote server returned an error: (550) File unavailable (e.g., file not found, no access)." MessageBox.Show(exp.Status.ToString()); //ProtcolError MessageBox.Show(resp.StatusCode.ToString()); // ActionNotTakenFileUnavailable MessageBox.Show(resp.StatusDescription.ToString()); //"550 SIZE: Operation not permitted\r\n" } This code does work, however, when connected to my personal FTP. The StatusDescription of the response says that the operation is "not permitted". Could it be that my office FTP just wont allow for the querying of a file size? I've also tried listing the directory details, which will return the size, and have noticed that my office FTP reports the directory details in a different format then my personal FTP. Maybe this is the problem? //work ftp ListDirectoryDetails -rw-r--r-- 1 (?) user 12345 Nov 16 20:28 some file name.xxx //personal ftp ListDirectoryDetails -rw-r--r-- 1 user user 12345 Mar 13 some file name.xxx From reading this blog post I think that my personal ftp is returning a Unix formatted response, but my work is returning a windows formatted response. Maybe this is unrelated but I thought I'd mention it.

    Read the article

  • The following code to check if a file exists on a server does not work

    - by xplorer2k
    Hi Everyone, I found the following code to check if a file exists on a server, but is not working for me. It tells me that "test1.tx" does not exist even though the file exists and its size is 498 bytes. If I try with Ftp.ListDirectory it tells me that the file does not exist. If I try with Ftp.GetFileSize it does not provide any results and the debugger's immediate gives me the following message: A first chance exception of type 'System.Net.WebException' occurred in System.dll. Using "request.UseBinary = true" does not make any difference. I have posted this same question at this link: http://social.msdn.microsoft.com/Forums/en-US/ncl/thread/89e05cf3-189f-48b7-ba28-f93b1a9d44ae Could someone help me how to fix it? private void button1_Click(object sender, EventArgs e) { string ftpServerIP = txtIPaddress.Text.Trim(); string ftpUserID = txtUsername.Text.Trim(); string ftpPassword = txtPassword.Text.Trim(); try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerIP + "//tmp/test1.txt"); request.Method = WebRequestMethods.Ftp.ListDirectory; //request.Method = WebRequestMethods.Ftp.GetFileSize; request.Credentials = new NetworkCredential(ftpUserID, ftpPassword); //request.UseBinary = true; using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { // Okay. textBox1.AppendText(Environment.NewLine); textBox1.AppendText("File exist"); } } catch (WebException ex) { if (ex.Response != null) { FtpWebResponse response = (FtpWebResponse)ex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { // Directory not found. textBox1.AppendText(Environment.NewLine); textBox1.AppendText("File does not exist"); } } } } Thanks very much, xplorer2k

    Read the article

  • WebRequest using SSL

    - by pm_2
    I have the following code to retrieve a file using FTP (which works fine). FtpWebRequest request = (FtpWebRequest)WebRequest.Create(svrPath); request.KeepAlive = true; request.UsePassive = true; request.UseBinary = true; request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(uname, passw); using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream)) using (StreamWriter destination = new StreamWriter(destinationFile)) { destination.Write(reader.ReadToEnd()); destination.Flush(); } However, when I try to do this using SSL, I am unable to access the file, as follows: FtpWebRequest request = (FtpWebRequest)WebRequest.Create(svrPath); request.KeepAlive = true; request.UsePassive = true; request.UseBinary = true; // The following line causes the download to fail request.EnableSsl = true; request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(uname, passw); using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream)) using (StreamWriter destination = new StreamWriter(destinationFile)) { destination.Write(reader.ReadToEnd()); destination.Flush(); } Can anyone tell me why the latter would not work?

    Read the article

  • FTP server returned 500 error with ASP.NET C#

    - by ffffff
    I 'm developing FTP exe ASP.NET?C#2.0 . but I FTP server returned 500 error FtpWebRequest myReq; FtpWebResponse myRes; myReq = (FtpWebRequest)WebRequest.Create("ftp://test/aaa.txt"); myReq.Credentials = new NetworkCredential("xxxx", "xxxx"); myReq.Method = WebRequestMethods.Ftp.DownloadFile; myRes = (FtpWebResponse)myReq.GetResponse(); // here error occured What's wrong?

    Read the article

  • ProgressBar isn't updating

    - by Nuru Salihu
    I have a progressbar that that is show progress returned by the backgroundworker do_dowork event like below . if (ftpSourceFilePath.Scheme == Uri.UriSchemeFtp) { FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(ftpSourceFilePath); NetworkCredential objCredential = new NetworkCredential(userName, password); objRequest.Credentials = objCredential; objRequest.Method = WebRequestMethods.Ftp.DownloadFile; FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse(); StreamReader objReader = new StreamReader(objResponse.GetResponseStream()); int len = 0; int iProgressPercentage = 0; FileStream objFS = new FileStream((cd+"\\VolareUpdate.rar"), FileMode.Create, FileAccess.Write, FileShare.Read); while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) > 0) { objFS.Write(buffer, 0, len); iRunningByteTotal += len; double dIndex = (double)(iRunningByteTotal); double dTotal = (double)buffer.Length; double dProgressPercentage = (dIndex / dTotal); iProgressPercentage = (int)(dProgressPercentage); if (iProgressPercentage > 100) { iProgressPercentage = 100; } bw.ReportProgress(iProgressPercentage); } } However, my progressbar does not update. While searching , i was told the UI thread is being blocked and then i thought may be passing the progress outside the loop will do the trick. then i change to this if (ftpSourceFilePath.Scheme == Uri.UriSchemeFtp) { FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(ftpSourceFilePath); NetworkCredential objCredential = new NetworkCredential(userName, password); objRequest.Credentials = objCredential; objRequest.Method = WebRequestMethods.Ftp.DownloadFile; FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse(); StreamReader objReader = new StreamReader(objResponse.GetResponseStream()); int len = 0; int iProgressPercentage = 0; FileStream objFS = new FileStream((cd+"\\VolareUpdate.rar"), FileMode.Create, FileAccess.Write, FileShare.Read); while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) > 0) { objFS.Write(buffer, 0, len); iRunningByteTotal += len; double dIndex = (double)(iRunningByteTotal); double dTotal = (double)buffer.Length; double dProgressPercentage = (dIndex / dTotal); iProgressPercentage = (int)(dProgressPercentage); if (iProgressPercentage > 100) { iProgressPercentage = 100; } // System.Threading.Thread.Sleep(2000); iProgressPercentage++; // SetText("F", true); } bw.ReportProgress(iProgressPercentage); progressBar.Refresh(); } However still didn't help. When i put break point in my workerprogresschanged event, it show the progressbar.value however does not update. I tried progressbar.update(0, i also tried sleeping the thread for a while in the loop still didn't help. Please any suggestion/help would be appreciated .

    Read the article

  • FTP OVER SSL - Invalid Token Error

    - by crazsmith
    I am trying to implement FTP over SSL to upload encrypted files. I've created a SSL certificate and send it to the vendor. But I couldn't make a FTPS connection to the server. When connecting via FTPS, I'm authenticating using my private key file. I have tried .NET FTPWebRequest, SmartFTp,CuteFTP Pro. I am getting the following error:- A call to SSPI failed. See inner exception. The inner exception is "The token supplied to the function is invalid" FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://RemoteHost.Com"); request.Credentials = new NetworkCredential("UserName", "Password"); request.KeepAlive = false; request.EnableSsl = true; X509Certificate2 cert2 = new X509Certificate2("PrivateKeyFile.pfx", "password"); request.ClientCertificates.Add(cert2); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Any Help Appreciated. Thanks.

    Read the article

  • Getting error while transfering PGP file through FTP : The underlying connection was closed: An unex

    - by sumeet Sharma
    I am trying to upload a PGP encrypted file through FTP. But I am getting an error message as follows: The underlying connection was closed: An unexpected error occurred on a receive. I am using the following code and getting the error at line: Stream ftpStream = response.GetResponse(); Is there any one who can help me out ASAP. Following is the code sample: FtpWebRequest request = WebRequest.Create("ftp://ftp.website.com/sample.txt.pgp") as FtpWebRequest; request.UsePassive = true; FtpWebResponse response = request.GetResponse() as FtpWebResponse; Stream ftpStream = response.GetResponse(); int bufferSize = 8192; byte[] buffer = new byte[bufferSize]; using (FileStream fileStream = new FileStream("localfile.zip", FileMode.Create, FileAccess.Write)) { int nBytes; while((nBytes = ftpStream.Read(buffer, 0, bufferSize) > 0) { fileStream.Write(buffer, 0, nBytes); } } Regards, Sumeet

    Read the article

  • ftp : get list of files

    - by Rohan
    I am trying to get a list of files on FTP folder. The code was working when I ran it locally, but on deploying it I started receiving html instead of file name ArrayList fName = new ArrayList(); try { StringBuilder result = new StringBuilder(); //create the directory FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(new Uri(directory)); requestDir.Method = WebRequestMethods.Ftp.ListDirectory; requestDir.Credentials = new NetworkCredential(FTP_USER_NAME, FTP_PASSWORD); requestDir.UsePassive = true; requestDir.UseBinary = true; requestDir.KeepAlive = false; requestDir.Proxy = null; FtpWebResponse response = (FtpWebResponse)requestDir.GetResponse(); Stream ftpStream = response.GetResponseStream(); StreamReader reader = new StreamReader(ftpStream, Encoding.ASCII); while (!reader.EndOfStream) { fName.Add(reader.ReadLine().ToString()); } response.Close(); ftpStream.Close(); reader.Close();

    Read the article

  • C# How to download files from FTP Server

    - by user3696888
    I'm trying to download a file (all kinds of files, exe dll txt etc.). And when I try to run it an error comes up on: using (FileStream ws = new FileStream(destination, FileMode.Create)) This is the error message: Access to the path 'C:\Riot Games\League of Legends\RADS\solutions \lol_game_client_sln\releases\0.0.1.41\deploy'(which is my destination, where I want to save it) is denied. Here is my code void download(string url, string destination) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url); request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential("user", "password"); request.UseBinary = true; using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { using (Stream rs = response.GetResponseStream()) { using (FileStream ws = new FileStream(destination, FileMode.Create)) { byte[] buffer = new byte[2048]; int bytesRead = rs.Read(buffer, 0, buffer.Length); while (bytesRead > 0) { ws.Write(buffer, 0, bytesRead); bytesRead = rs.Read(buffer, 0, buffer.Length); } } } }

    Read the article

  • Strange File Upload issue with asp.net site on a web farm

    - by Coov
    I have a basic asp.net file upload page. When I test file uploads from my local machine, it works fine. When I test file uploads from our dev machine, it works fine. When I deploy the site to our production webfarm, it behaves strangely. If I access the site from off the network, I can load file-after-file without issue. If I access the site from within our network, I can load the first file just fine but any subsequent files result it a bad sequence of commands error. I'm not sure if this is web farm issue, a network issue, or something else. It feels like a connection is not being disposed of properly but it doesn't make sense why everything works fine remotely. Markup: <asp:FileUpload ID="FileUpload1" runat="server" Width="350px" /> <asp:Button ID="btnSubmit" runat="server" Text="Upload" onclick="btnSubmit_Click" /> Code: if (FileUpload1.HasFile) { FtpWebRequest ftpRequest; FtpWebResponse ftpResponse; ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://ftp.myftpsite.com/" + FileUpload1.FileName)); ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; ftpRequest.Proxy = null; ftpRequest.UseBinary = true; ftpRequest.Credentials = new NetworkCredential("username", "password"); ftpRequest.KeepAlive = false; byte[] fileContents = new byte[FileUpload1.PostedFile.ContentLength]; using (Stream fr = FileUpload1.PostedFile.InputStream) { fr.Read(fileContents, 0, FileUpload1.PostedFile.ContentLength); } using (Stream writer = ftpRequest.GetRequestStream()) { writer.Write(fileContents, 0, fileContents.Length); } ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); Response.Write(ftpResponse.StatusDescription); }

    Read the article

  • Ftp throws WebException only in .NET 4.0

    - by Trakhan
    I have following c# code. It runs just fine when compiled against .NET framework 3.5 or 2.0 (I did not test it against 3.0, but it will most likely work too). The problem is, that it fails when built against .NET framework 4.0. FtpWebRequest Ftp = (FtpWebRequest)FtpWebRequest.Create(Url_ + '/' + e.Name); Ftp.Method = WebRequestMethods.Ftp.UploadFile; Ftp.Credentials = new NetworkCredential(Login_, Password_); Ftp.UseBinary = true; Ftp.KeepAlive = false; Ftp.UsePassive = true; Stream S = Ftp.GetRequestStream(); byte[] Content = null; bool Continue = false; do { try { Continue = false; Content = File.ReadAllBytes(e.FullPath); } catch (Exception) { Continue = true; System.Threading.Thread.Sleep(500); } } while (Continue); S.Write(Content, 0, Content.Length); S.Close(); FtpWebResponse Resp = (FtpWebResponse)Ftp.GetResponse(); if (Resp.StatusCode != FtpStatusCode.CommandOK) Console.WriteLine(Resp.StatusDescription); The problem is in call Stream S = Ftp.GetRequestStream();, which throws an en instance of WebException with message “The remote server returned an error: (500) Syntax error, command unrecognized”. Does anybody know why it is so? PS. I communicate virtual ftp server in ECM Alfresco.

    Read the article

  • Uploading an xml direct to ftp

    - by Joshua Maerten
    i put this direct below a button: XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("Login"); XmlElement id = doc.CreateElement("id"); id.SetAttribute("userName", usernameTxb.Text); id.SetAttribute("passWord", passwordTxb.Text); XmlElement name = doc.CreateElement("Name"); name.InnerText = nameTxb.Text; XmlElement age = doc.CreateElement("Age"); age.InnerText = ageTxb.Text; XmlElement Country = doc.CreateElement("Country"); Country.InnerText = countryTxb.Text; id.AppendChild(name); id.AppendChild(age); id.AppendChild(Country); root.AppendChild(id); doc.AppendChild(root); // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://users.skynet.be"); request.Method = WebRequestMethods.Ftp.UploadFile; request.UsePassive = false; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("fa490002", "password"); // Copy the contents of the file to the request stream. StreamReader sourceStream = new StreamReader(); 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(); response.Close(); MessageBox.Show("Created SuccesFully!"); this.Close(); but i always get an error of the streamreader path, what do i need to place there ? the meening is, creating an account and when i press the button, an xml file is saved to, ftp://users.skynet.be/testxml/ the filename is from usernameTxb.Text + ".xml".

    Read the article

  • My C# UploadFile method successfully uploads a file, but then my UI hangs...

    - by kyrathaba
    I have a simple WinForms test application in C#. Using the following method, I'm able to upload a file when I invoke the method from my button's Click event handler. The only problem is: my Windows Form "freezes". I can't close it using the Close button. I have to end execution from within the IDE (Visual C# 2010 Express edition). Here are the two methods: public void UploadFile(string FullPathFilename) { string filename = Path.GetFileName(FullPathFilename); try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(_remoteUser, _remotePass); StreamReader sourceStream = new StreamReader(FullPathFilename); byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); request.ContentLength = fileContents.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); response.Close(); requestStream.Close(); sourceStream.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Upload error"); } finally { } } which gets called here: private void btnUploadTxtFile_Click(object sender, EventArgs e) { string username = "my_username"; string password = "my_password"; string host = "ftp://mywebsite.com"; try { clsFTPclient client = new clsFTPclient(host + "/httpdocs/non_church/", username, password); client.UploadFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\myTextFile.txt"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Upload problem"); } }

    Read the article

  • using ftpWebRequest with an error: the remote server returned error 530 not loged in

    - by user1361207
    I am trying to use the ftpWebRequest in c# my code is // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://192.168.20.10/file.txt"); request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("dev\ftp", "devftp"); // Copy the contents of the file to the request stream. StreamReader sourceStream = new StreamReader(@"\file.txt"); byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); request.ContentLength = fileContents.Length; request.UsePassive = true; 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(); and I get an Error in request.GetRequestStream(); the error is: the remote server returned error 530 not loged in if I try to go in to a browser page and in the url I write ftp://192.168.20.10/ the brows page is asking me for a name and password, I put the same name and password and I see all the files and folders in the ftp folder. can any one help me with this problem?

    Read the article

  • Create folder on ftp

    - by Afnan
    I am using method to create folder on ftp i want get exception if folder already exsists how to make it over write the existing folder using System; using System.Net; class Test { static void Main() { WebRequest request = WebRequest.Create("ftp://host.com/directory"); request.Method = WebRequestMethods.Ftp.MakeDirectory; request.Credentials = new NetworkCredential("user", "pass"); using (var resp = (FtpWebResponse) request.GetResponse()) { Console.WriteLine(resp.StatusCode); } } } it is "remote server returned error (550) file not found"

    Read the article

  • The server returned an address in response to the PASV command that is different than the address to

    - by senzacionale
    {System.Net.WebException: The server returned an address in response to the PASV command that is different than the address to which the FTP connection was made. at System.Net.FtpWebRequest.CheckError() at System.Net.FtpWebRequest.SyncRequestCallback(Object obj) at System.Net.CommandStream.Abort(Exception e) at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage) at System.Net.FtpWebRequest.GetRequestStream() at BackupDB.Program.FTPUploadFile(String serverPath, String serverFile, FileInfo LocalFile, NetworkCredential Cred) in D:\PROJEKTI\BackupDB\BackupDB\Program.cs:line 119} code: FTPMakeDir(new Uri(serverPath + "/"), Cred); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath + serverFile); request.UsePassive = true; request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = Cred; byte[] buffer = new byte[10240]; // Read/write 10kb using (FileStream sourceStream = new FileStream(LocalFile.ToString(), FileMode.Open)) { using (Stream requestStream = request.GetRequestStream()) { int bytesRead; do { bytesRead = sourceStream.Read(buffer, 0, buffer.Length); requestStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } response = (FtpWebResponse)request.GetResponse(); response.Close(); }

    Read the article

  • Crossthread exception and invokerequired solution doesn't change my control value

    - by Pilouk
    EDIT Solution : Here i'm setting my byref value in each object then i'm running a backgroundworker Private Sub TelechargeFichier() Dim DocManquant As Boolean = False Dim docName As String = "" Dim lg As String = "" Dim telechargementFini As Boolean = False lblMessage.Text = EasyDealChangeLanguage.Instance.GetStringFromResourceName("1478") prgBar.Maximum = m_listeFichiers.Count For i As Integer = 0 To m_listeFichiers.Count - 1 m_listeFichiers(i).Set_ByRefLabel(lblMessage) m_listeFichiers(i).Set_ByRefPrgbar(prgBar) m_listeThreads.Add(New Thread(AddressOf m_listeFichiers(i).DownloadMe)) Next m_bgWorker = New BackgroundWorker m_bgWorker.WorkerReportsProgress = True AddHandler m_bgWorker.DoWork, AddressOf DownloadFiles m_bgWorker.RunWorkerAsync() ''Completed 'lblMessage.Text = EasyDealChangeLanguage.Instance.GetStringFromResourceName("1383") 'Me.DialogResult = System.Windows.Forms.DialogResult.OK End Sub Here is my downloadFiles function : Note that each start will do the downloadMe function see below too Private Sub DownloadFiles(sender As Object, e As DoWorkEventArgs) For i As Integer = 0 To m_listeThreads.Count - 1 m_listeThreads(i).Start() Next For i As Integer = 0 To m_listeThreads.Count - 1 m_listeThreads(i).Join() Next End Sub I have multiple thread that each will download a ftp file. I would like that each file that have been completed will set a value to a progress bar and a label from my UI thread. For some reason invokerequired never change to false. Here is my little function that start all the thread Private Sub TelechargeFichier() Dim DocManquant As Boolean = False Dim docName As String = "" Dim lg As String = "" Dim telechargementFini As Boolean = False lblMessage.Text = EasyDealChangeLanguage.Instance.GetStringFromResourceName("1478") prgBar.Maximum = m_listeFichiers.Count For i As Integer = 0 To m_listeFichiers.Count - 1 m_listeFichiers(i).Set_ByRefLabel(lblMessage) m_listeFichiers(i).Set_ByRefPrgbar(prgBar) m_listeThreads.Add(New Thread(AddressOf m_listeFichiers(i).DownloadMe)) Next For i As Integer = 0 To m_listeThreads.Count - 1 m_listeThreads(i).Start() Next For i As Integer = 0 To m_listeThreads.Count - 1 m_listeThreads(i).Join() Next 'Completed lblMessage.Text = EasyDealChangeLanguage.Instance.GetStringFromResourceName("1383") Me.DialogResult = System.Windows.Forms.DialogResult.OK End Sub Here my property that hold the Byref control from the UI thread. This is in my object which content the addressof function that will download the file (DownloadMe) Public Sub Set_ByRefPrgbar(ByRef prgbar As ProgressBar) m_prgBar = prgbar End Sub Public Sub Set_ByRefLabel(ByRef lbl As EasyDeal.Controls.EasyDealLabel3D) m_lblMessage = lbl End Sub Here is the download function : Public Sub DownloadMe() Dim ftpReq As FtpWebRequest Dim ftpResp As FtpWebResponse = Nothing Dim streamInput As Stream Dim fileStreamOutput As FileStream Try ftpReq = CType(WebRequest.Create(EasyDeal.Controls.Common.FTP_CONNECTION & m_downloadFtpPath & m_filename), FtpWebRequest) ftpReq.Credentials = New NetworkCredential(FTP_USER, FTP_PASS) ftpReq.Method = WebRequestMethods.Ftp.DownloadFile ftpResp = ftpReq.GetResponse streamInput = ftpResp.GetResponseStream() fileStreamOutput = New FileStream(m_outputPath, FileMode.Create, FileAccess.ReadWrite) ReadWriteStream(streamInput, fileStreamOutput) Catch ex As Exception 'Au pire la fichier sera pas downloader Finally If ftpResp IsNot Nothing Then ftpResp.Close() End If Dim nomFichier As String = m_displaynameEN If EasyDealChangeLanguage.GetCurrentLanguageTypes = EasyDealChangeLanguage.EnumLanguageType.Francais Then nomFichier = m_displaynameFR End If If m_lblMessage IsNot Nothing Then EasyDealCommon.TH_SetControlText(m_lblMessage, String.Format(EasyDealChangeLanguage.Instance.GetStringFromResourceName("1479"), nomFichier)) End If If m_prgBar IsNot Nothing Then EasyDealCommon.TH_SetPrgValue(m_prgBar, 1) End If End Try End Sub Here is the crossthread invoke solution function : Public Sub TH_SetControlText(ByVal ctl As Control, ByVal text As String) If ctl.InvokeRequired Then ctl.BeginInvoke(New Action(Of Control, String)(AddressOf TH_SetControlText), ctl, text) Else ctl.Text = text End If End Sub Public Sub TH_SetPrgValue(ByVal prg As ProgressBar, ByVal value As Integer) If prg.InvokeRequired Then prg.BeginInvoke(New Action(Of ProgressBar, Integer)(AddressOf TH_SetPrgValue), prg, value) Else prg.Value += value End If End Sub The problem is the invokerequired never get to false it actually goes in to beginInvoke but never end in the Else section to set the value.

    Read the article

1