0

I'm trying to read all text and replace certain text in a specific location. That location needs to have the username.

File path:

C:\Users\zmatar\AppData\Roaming\NexJen Systems\My

Here is what I have. I get an error saying it cannot find the location. What I was going to do is maybe pass it to a label and then add the label into the location? idk

string text = File.ReadAllText(@"C:\Users\System.Environment.UserName\AppData\Roaming\NexJen Systems\My\IsisSettings.isis");
text = text.Replace("172.16.1.24", "172.16.1.23");
File.WriteAllText(@"C:\Users\System.Environment.UserName\AppData\Roaming\NexJen Systems\My\IsisSettings.isis", text);
Billyhoe5
  • 85
  • 1
  • 8

1 Answers1

6

Use Path.Combine to build your pathname with the Environment.SpecialFolder enum to retrieve the current user roaming folder. This removes the hard coding of the Environment.UserName in the path of the current user roaming folder. It is not mandatory to have the username as part of a user folder in the default position on local disk See Folder Redirection.

string basePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullPath = Path.Combine(basePath, @"NexJen Systems\My\IsisSettings.isis");
string text = File.ReadAllText(fullPath);
text = text.Replace("172.16.1.24", "172.16.1.23");
File.WriteAllText(fullPath, text);

You could find a nice explanation about Environment.SpecialFolder in this answer and also some advices about using this folder.

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286