I am just starting to learn C# and I am trying to replace all occurrences of a certain substring in a text file with a \ if the text is not separated by whitespace or not . What is the easiest way to do this? Thanks.
            Asked
            
        
        
            Active
            
        
            Viewed 3,149 times
        
    0
            
            
        - 
                    2Can you show an example of what the input and output could and should be, please? It's a little hard to understand what you mean from your question. – Ry- Apr 20 '13 at 15:55
- 
                    take a look at: http://stackoverflow.com/questions/1915632/open-a-file-and-replace-strings-in-c-sharp – MUG4N Apr 20 '13 at 15:55
- 
                    1I learned programming using python and just started C# this week so to be honest I have not even gotten close to a correct solution. – Padraic Cunningham Apr 20 '13 at 15:56
- 
                    @minitech I am trying to parse a txt file and change every occurrence of the sub string "BACKS" to an actual "\". – Padraic Cunningham Apr 20 '13 at 16:01
2 Answers
10
            - read in your file: - var fileContents = System.IO.File.ReadAllText(@"C:\YourFile.txt");
- replace text: - fileContents = fileContents.Replace("BACKS", "\\");
- write the file to filesystem: - System.IO.File.WriteAllText(@"C:\YourFile.txt", fileContents);
 
    
    
        MUG4N
        
- 19,377
- 11
- 56
- 83
1
            
            
        if you wanna use Regex
Simple and single statement
File.WriteAllText("c:\\test.txt", Regex.Replace(File.ReadAllText("c:\\test.txt"), @"\bBACKS\b", "\\"));
 
    
    
        Civa
        
- 2,058
- 2
- 18
- 30
- 
                    Thanks Civa that worked well too. why do I need to use double \\ on path when using regex as opposed to single \ when using MUG4N'S method? – Padraic Cunningham Apr 20 '13 at 16:38
- 
                    it's because of the @ sign in my code. See: http://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-in-c – MUG4N Apr 20 '13 at 16:59
