使用System.Environment.Username读取所有文本

本文关键字:文本 读取 Username System Environment 使用 | 更新日期: 2023-09-27 18:22:38

我正在尝试读取所有文本并替换特定位置的某些文本。该位置需要有用户名。

文件路径:

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

这是我的东西。我收到一个错误,说它找不到位置。我要做的是把它传给一个标签,然后把标签添加到这个位置?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);

使用System.Environment.Username读取所有文本

使用Path.Combine来构建您的路径名和Environment.SpecialFolder枚举,以检索当前用户漫游文件夹。这删除了当前用户漫游文件夹路径中Environment.UserName的硬编码。将用户名作为用户文件夹的一部分放在本地磁盘上的默认位置不是强制性的。请参阅文件夹重定向。

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);

你可以在这个答案中找到关于Environment.SpecialFolder的一个很好的解释,以及关于使用这个文件夹的一些建议。