Editing a text file, any easier way?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • babbsagg
    New Member
    • Apr 2012
    • 1

    Editing a text file, any easier way?

    I just want to edit a txt and save the edited version.

    In this case i replaced all the i's with q's.

    Is there an easier way to do this? Without all the casting?

    Code:
    static void Main(string[] args){
    
         string[] text = File.ReadAllLines("test.txt");
         char[] help;
    
         for (int i = 0; i < text.Length; i++) {
    
             help = text[i].ToArray();
    
             for (int j = 0; j < help.Length; j++){
    
                  if (help[j] == 'i')
                      help[j] = 'q';
             }
    
             text[i] = new String(help);
                    
         }
         File.WriteAllLines("test_alt.txt",text);
    }
    }
  • RhysW
    New Member
    • Mar 2012
    • 70

    #2
    Code:
                List<string> text = new List<string>();
                string filelocation = null;
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    filelocation = openFileDialog1.FileName.ToString();
                }
                foreach (string line in File.ReadLines(filelocation))
                {
                    string addthis;
                    if (line.Contains("i"))
                    {
                        addthis = line.Replace("i", "j");
                    }
                    else
                    {
                        addthis = line;
                    }
                    text.Add(addthis);
                }
                File.WriteAllLines(filelocation, text);
    there is this method, you throw it once into a string, replace all i's to j's and then write the list back, there is a fiddly bit in the middle where line isnt added but addthis is, beause i couldnt set it as line = line.replace("i ","j"); or the compiler throws a wobbly because line is used for the rest of the loop, so i made the new string addthis that is always added, if the string contains an i they are turned to j's, assigned to addthis, and add this gets added, otherwise addthis is just directly equal to line, im sure there is a neater way of doing this but you asked for me to get rid of the castings so this was a quick throw together.

    Comment

    Working...