none
Replace a text in ftp txt RRS feed

  • Question

  • Guys i really need help how do i replace a text i have a code for a normal txt in pc

                string text = File.ReadAllText("test.txt");
                text = text.Replace("3", "there was nuber 3");
                File.WriteAllText("test.txt", text);

    and i need to do that code but just to my ftp file (txt).

    thanks for the help

    Wednesday, November 21, 2018 3:16 PM

Answers

  • Hi Noam1248,

    Thank you for posting here.

    For your question, you want to replace the string in the txt file in ftp.

    Please try  this  code below.

      private void button1_Click(object sender, EventArgs e)
    
            {
    
                string path = @"ftp://ftpipaddress/test.txt";
    
                string username = "yourusername";
    
                string password = "yourpassword";           
    
            FtpUploadString(textBox1.Text, path, username, password);
    
            }
    
            private void FtpUploadString(string text, string to_uri, string user_name, string password)
    
            {
    
                FtpWebRequest request =
    
                    (FtpWebRequest)WebRequest.Create(to_uri);
    
                request.Method = WebRequestMethods.Ftp.UploadFile;
    
                request.Credentials =
    
                    new NetworkCredential(user_name, password);
    
                request.ContentLength = FtpdownloadString(to_uri, user_name, password).Length;
    
                string fi = FtpdownloadString(to_uri, user_name, password);
    
                using (Stream request_stream = request.GetRequestStream())
    
                {
    
                    byte[] bytes = Encoding.UTF8.GetBytes(fi);
    
                    request_stream.Write(bytes, 0, (fi).Length);
    
                    request_stream.Close();
    
                }
    
                MessageBox.Show("success");
    
            }
    
            private string FtpdownloadString(string to_uri, string user_name, string password)
    
            {
    
                FtpWebRequest request =
    
                    (FtpWebRequest)WebRequest.Create(to_uri);
    
                request.Method = WebRequestMethods.Ftp.DownloadFile;
    
                request.Credentials =
    
                    new NetworkCredential(user_name, password);
    
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    
                Stream ftpStream = response.GetResponseStream();
    
                StreamReader reader = new StreamReader(ftpStream);
    
                string filestr = reader.ReadToEnd();
    
                filestr = filestr.Replace("3", textBox1.Text);
    
                return filestr;
    
            }


    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Noam1248 Thursday, November 22, 2018 1:53 PM
    Thursday, November 22, 2018 8:11 AM
    Moderator

All replies

  • Hello, 

    Can you, pls, explain what you understand under "ftp file"?


    Sincerely, Highly skilled coding monkey.

    Wednesday, November 21, 2018 3:28 PM
  • FTP is just file upload/download. You cannot manipulate the file that is there directly.

    1. Download the file from the FTP server to a temp file.
    2. Change the file using the code you already have.
    3. Upload the file back to the FTP server, replacing the original file.

    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, November 21, 2018 3:30 PM
    Moderator
  • no but i need in code to do that automatically
    Wednesday, November 21, 2018 3:32 PM
  • in my ftp in will go to the txt file and search for the text explain '3' and remove that and replace it with the text on website
    Wednesday, November 21, 2018 3:34 PM
  • I don't understand. Are you running code directly on the FTP server such that you have access to the underlying file system. FTP is just a view sitting over the file system. In this case you can modify the files directly (ignoring security) so your code would work if the path is correct.

    If you are on a remote machine then you cannot manipulate the file directly. Here's the list of commands available for FTP (at least for Windows). None of them allow you to replace text in a file. The only "file manipulation" command is to append to an existing file. Upload/download is the only option remotely.


    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, November 21, 2018 3:45 PM
    Moderator
  • i just told you i need

                string text = File.ReadAllText("test.txt");
                text = text.Replace("3", "there was nuber 3");
                File.WriteAllText("test.txt", text);

    that but i dont want to change on my pc the text i need on my ftp server just that code ^

    copy paste but to the ftp server on text file.

    Wednesday, November 21, 2018 3:55 PM
  • With your FTP you can do very few thinks. Each of thinks named COMMAND.

    List of commands are here https://en.wikipedia.org/wiki/List_of_FTP_commands

    FTP would not do anything outside this list, but may not support even each of the Command.

    The only option you have to complete the task - follow the instruction CoolDadTx already provide:

    - download, modify, upload.




    Sincerely, Highly skilled coding monkey.

    Wednesday, November 21, 2018 4:22 PM
  • You can't. The file APIs do not support URLs, just UNC. You have to use FtpRequest and it doesn't support text replacement. The earlier solution is the only one that I can think of.

    What is wrong with downloading the file to a temp path, updating it and then uploading it back? Why can't you do this?


    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, November 21, 2018 4:35 PM
    Moderator
  •     public class File
        {
            public class Config
            {
                public string Url { get; set; }
                public string UserName { get; set; }
                public string PassWord { get; set; }
    
                public override string ToString()
                {
                    return $"ftp://{UserName}:{PassWord}@{Url}/";
                }
            }
            
            static File instance = new File();
            Config config;
            object lockObject = new Object();
    
            public static void SetConfig(Config config)
            {
                if(instance.config == null)
                    lock(instance.lockObject)
                        if (instance.config == null)
                            instance.config = config;
            }
    
            private string readAllText(string fileName)
            {
                WebRequest request = FtpWebRequest.Create(config.ToString() + fileName);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
    
                using (var stream = request.GetResponse().GetResponseStream())
                    using (var reader = new StreamReader(stream))
                        return reader.ReadToEnd();
            }
    
            public static string ReadAllText(string fileName)
            {
                return instance.readAllText(fileName);
            }
        }
                File.SetConfig(new File.Config
                {
                    Url = "ftp.server.com",
                    UserName = "user",
                    PassWord = "pw"
                });
    
                var fileText = File.ReadAllText("www/index.php");

    If you necessarily want to call it like File.ReadAllText(...) you can use this solution. But without setting the ftp connection data it's not possible. And it's not safe... You need to implement a method to upload the file again after editing...

    Greetings, Chris

    Wednesday, November 21, 2018 5:49 PM
  •     public class File
        {
            public class Config
            {
                public string Url { get; set; }
                public string UserName { get; set; }
                public string PassWord { get; set; }
    
                public override string ToString()
                {
                    return $"ftp://{UserName}:{PassWord}@{Url}/";
                }
            }
            
            static File instance = new File();
            Config config;
            object lockObject = new Object();
    
            public static void SetConfig(Config config)
            {
                if(instance.config == null)
                    lock(instance.lockObject)
                        if (instance.config == null)
                            instance.config = config;
            }
    
            private string readAllText(string fileName)
            {
                WebRequest request = FtpWebRequest.Create(config.ToString() + fileName);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
    
                using (var stream = request.GetResponse().GetResponseStream())
                    using (var reader = new StreamReader(stream))
                        return reader.ReadToEnd();
            }
    
            public static string ReadAllText(string fileName)
            {
                return instance.readAllText(fileName);
            }
    
            private void writeAllText(string fileName, string text)
            {
                var request = (FtpWebRequest)WebRequest.Create
                    ($"ftp://{config.Url}/{fileName}");
                request.Credentials = new NetworkCredential(config.UserName, config.PassWord);
                request.Method = WebRequestMethods.Ftp.GetFileSize;
    
                try
                {
                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                }
                catch (WebException ex)
                {
                    FtpWebResponse response = (FtpWebResponse)ex.Response;
                    if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                    {
                        response.Dispose();
                        var deleteRequest = (FtpWebRequest)WebRequest.Create
                            ($"ftp://{config.Url}/{fileName}");
                        deleteRequest.Credentials = new NetworkCredential(config.UserName, config.PassWord);
                        deleteRequest.Method = WebRequestMethods.Ftp.DeleteFile;
                        response = (FtpWebResponse)deleteRequest.GetResponse();
                        if (response.StatusCode != FtpStatusCode.CommandOK)
                            throw new Exception("Delete file error");
    
                    }
                    var uploadRequest = (FtpWebRequest)WebRequest.Create
                    ($"ftp://{config.Url}/{fileName}");
                    uploadRequest.Credentials = new NetworkCredential(config.UserName, config.PassWord);
                    uploadRequest.Method = WebRequestMethods.Ftp.DeleteFile;
                    byte[] fileContents = Encoding.UTF8.GetBytes(text);
                    uploadRequest.ContentLength = fileContents.Length;
                    using (Stream requestStream = uploadRequest.GetRequestStream())
                    {
                        requestStream.Write(fileContents, 0, fileContents.Length);
                    }
                    using (FtpWebResponse responseUpload = (FtpWebResponse)uploadRequest.GetResponse())
                    {
                        Console.WriteLine($"Upload File Complete, status {responseUpload.StatusDescription}");
                    }
                }
            }
    
            public static void WriteAllText(string fileName, string text)
            {
                instance.writeAllText(fileName, text);
            }
        }

    I have not test it yet...

    Wednesday, November 21, 2018 7:06 PM
  • I have an error that says: System.Net.WebException: 'The remote server returned an error: (550) File unavailable (for example, not found, inaccessible).

    http://prntscr.com/llanvq

    Wednesday, November 21, 2018 7:42 PM
  • Maybe file not found or username password wrong
    Wednesday, November 21, 2018 8:22 PM
  • where i need to put the file details?

    my button is:

    File.SetConfig(new File.Config
                {
                    Url = "files.000webhost.com",
                    UserName = "username",
                    PassWord = "pass"
                });

                var fileText = File.ReadAllText("https://toxicaxe333.000webhostapp.com/test.txt");

    • Edited by Noam1248 Wednesday, November 21, 2018 8:31 PM
    Wednesday, November 21, 2018 8:30 PM
  • File.SetConfig(new File.Config
                {
                    Url = "files.000webhost.com",
                    UserName = "username",
                    PassWord = "pass"
                });
    
                var fileText = File.ReadAllText("test.txt");

    Wednesday, November 21, 2018 8:32 PM
  • no again error
    Wednesday, November 21, 2018 8:35 PM
  • no again error

    is the directory correct?

    var fileText = File.ReadAllText("www/abc/.../test.txt");

    Wednesday, November 21, 2018 8:37 PM
  • Yes it is fine but again error:

    File.SetConfig(new File.Config
                {
                    Url = "files.000webhost.com",
                    UserName = "user",
                    PassWord = "3"
                });

                var fileText = File.ReadAllText("https://toxicaxe333.000webhostapp.com/test.txt");



    • Edited by Noam1248 Wednesday, November 21, 2018 8:43 PM
    Wednesday, November 21, 2018 8:40 PM
  • Don't write your password here

    :O

    Wednesday, November 21, 2018 8:42 PM
  • omg forgot :(
    Wednesday, November 21, 2018 8:43 PM
  • so what about the error?
    Wednesday, November 21, 2018 8:45 PM
  • Server returns 530... Can you login via browser? ftp://files.000webhost.com

    PS:  ftp, txt... Ahron, is it you? xD


    • Edited by DerChris88 Wednesday, November 21, 2018 8:54 PM
    Wednesday, November 21, 2018 8:52 PM
  • my brother
    Wednesday, November 21, 2018 8:56 PM
  • my brother

    Aha ;)

    Can you connect to the ftp by using the link and your login data?

    And you have to remove this: var fileText = File.ReadAllText("https://toxicaxe333.000webhostapp.com/test.txt");

    Wednesday, November 21, 2018 9:01 PM
  • i can login in and i removed the var fileText = and still i have an error...
    • Edited by Noam1248 Wednesday, November 21, 2018 9:19 PM
    Wednesday, November 21, 2018 9:19 PM
  • Hi Noam1248,

    Thank you for posting here.

    For your question, you want to replace the string in the txt file in ftp.

    Please try  this  code below.

      private void button1_Click(object sender, EventArgs e)
    
            {
    
                string path = @"ftp://ftpipaddress/test.txt";
    
                string username = "yourusername";
    
                string password = "yourpassword";           
    
            FtpUploadString(textBox1.Text, path, username, password);
    
            }
    
            private void FtpUploadString(string text, string to_uri, string user_name, string password)
    
            {
    
                FtpWebRequest request =
    
                    (FtpWebRequest)WebRequest.Create(to_uri);
    
                request.Method = WebRequestMethods.Ftp.UploadFile;
    
                request.Credentials =
    
                    new NetworkCredential(user_name, password);
    
                request.ContentLength = FtpdownloadString(to_uri, user_name, password).Length;
    
                string fi = FtpdownloadString(to_uri, user_name, password);
    
                using (Stream request_stream = request.GetRequestStream())
    
                {
    
                    byte[] bytes = Encoding.UTF8.GetBytes(fi);
    
                    request_stream.Write(bytes, 0, (fi).Length);
    
                    request_stream.Close();
    
                }
    
                MessageBox.Show("success");
    
            }
    
            private string FtpdownloadString(string to_uri, string user_name, string password)
    
            {
    
                FtpWebRequest request =
    
                    (FtpWebRequest)WebRequest.Create(to_uri);
    
                request.Method = WebRequestMethods.Ftp.DownloadFile;
    
                request.Credentials =
    
                    new NetworkCredential(user_name, password);
    
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    
                Stream ftpStream = response.GetResponseStream();
    
                StreamReader reader = new StreamReader(ftpStream);
    
                string filestr = reader.ReadToEnd();
    
                filestr = filestr.Replace("3", textBox1.Text);
    
                return filestr;
    
            }


    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Noam1248 Thursday, November 22, 2018 1:53 PM
    Thursday, November 22, 2018 8:11 AM
    Moderator
  • thank you so much dude you helped me alot
    Thursday, November 22, 2018 1:54 PM