0

My code looks like this:

string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);     

I want to edit two words, not only one:

  • From SIDE to *SIDE
  • And BARCODE to *BARCODE

Also is there any solution to find the file by the end of its name instead of full name? Because the file name is always different but it always ends with a string like "_ABC.desc"

Koby Douek
  • 16,156
  • 19
  • 74
  • 103
Tamas555
  • 47
  • 10

3 Answers3

1

You can find file by the end of it's name

       string partialName = "text";  // ending part of file name
       DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(@"D:\");
       FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + partialName + ".*");    
       // All files matched that name will show in filesInDir
       foreach (FileInfo foundFile in filesInDir)
       {
           string fullName = foundFile.FullName;
           string text = File.ReadAllText(fullName);// here you will get text 
       }    
Manoj
  • 4,951
  • 2
  • 30
  • 56
  • string text = File.ReadAllText("test.txt"); And with your code what do i have to put instead of "test.txt" ? – Tamas555 Jul 28 '17 at 10:58
  • You can use `string text = File.ReadAllText(fullName);` See my updated answer @Tamas555 – Manoj Jul 28 '17 at 11:04
0

i would want to edit two words not only one: -From "SIDE" to "*SIDE" -And "BARCODE" to "*BARCODE"

You can call Replace() method again

text = text.Replace("some text", "new value").Replace("BARCODE","*BARCODE");

Also is there any solution to find the file by the end of it's name instead of full name?

NO, you will have to specify the actual and full file name along with it's path. Though you can use Directory.GetFiles() to get all file names and probably pass in a RegEx but that's your choice See this post

Getting all file names from a folder using C#

Rahul
  • 76,197
  • 13
  • 71
  • 125
0

To change words you want I would create an array of strings that contains original values and then use regular expression to find out which one to replace.

Example :

const string PATTERN = @"(?<!\*){0}";
string[] words = new string[] { "SIDE", "BARCODE" };

foreach(string word in words)
{
    Regex r = new Regex(string.Format(PATTERN, word));
    text = r.Replace(text, "*" + word);
}

This will ensure that "*BARCODE" wont be replaced with "**BARCODE" as would do using String.Replace method.

You can try this online


Second part, to find out files based on the partial input, is well described by @Manoj answer

mrogal.ski
  • 5,828
  • 1
  • 21
  • 30