英文:
After writing the file, part of the original file remains in the file
问题
在编写文件后,原始文件的一部分仍然存在于文件中。
我使用C#编写模块来保存软件设置,但我发现如果原始设置文件较长,覆盖后的新设置文件的末尾始终会保留前一次设置信息的尾部。
以下是我修改后的代码:
public void SaveToFile(string pathName)
{
try
{
using (var sw = new StreamWriter(
File.Open(
pathName,
FileMode.Create // 将 FileMode.OpenOrCreate 改为 FileMode.Create
)))
{
sw.Write(this.ToString());
XXXSystem.Log(this.ToString());
}
}
catch (Exception ex)
{
XXXSystem.Log("保存配置文件时发生错误:" + ex.ToString());
}
}
主要修改是将 FileMode.OpenOrCreate
更改为 FileMode.Create
,这将在写入文件之前清除文件内容,以确保不会保留原始文件的部分内容。
英文:
After writing the file, part of the original file remains in the file
I use C# to write modules to save software settings, but I found that if the original settings file is longer, the end of the new settings file after overwriting will always have the tail of the previous settings information.
Below is my changed code:
public void SaveToFile(string pathName)
{
try
{
using (var sw =new StreamWriter(
File. Open(
pathName,
FileMode. OpenOrCreate
)))
{
sw. Write(this. ToString());
XXXSystem.Log(this.ToString());
}
}
catch (Exception ex)
{
XXXSystem.Log("An error occurred while saving the configuration file: " + ex.ToString());
}
}
答案1
得分: 3
更新:
Oshawott提供了一个更清晰的替代方法:
new StreamWriter(pathName, false)
原始答案:
将
File.Open(pathName, FileMode.OpenOrCreate)
更改为
File.Open(pathName, FileMode.Create)
不同文件模式的描述在这里。您还可以在IDE中使用智能感知功能轻松查看它们。
此外,如果您正在使用IDE,请使用代码格式化功能。
英文:
Update:
Oshawott gave an even cleaner alternative:
new StreamWriter(pathName, false)
Original answer:
Change
File.Open(pathName, FileMode.OpenOrCreate)
To
File.Open(pathName, FileMode.Create)
The descriptions of the different file modes are here. You can also use intellisense in your IDE to see them easily.
Also - if you’re using an IDE, please use the code formatting features..
答案2
得分: 1
System.IO.File
类封装了许多常见的文件操作,包括能够将内容写入文件的 WriteAllText
方法。
WriteAllText
方法将使用您传递给它的字符串内容创建一个新文件(或覆盖现有文件):
public void SaveToFile(string path)
{
try
{
// 创建文件,如果文件存在则覆盖。
File.WriteAllText(path, this.ToString());
XXXSystem.Log(this.ToString());
}
catch (Exception ex)
{
XXXSystem.Log(
$"保存配置文件时发生错误:{ex}";
}
}
英文:
The System.IO.File
class wraps a lot of common file actions, including the ability to WriteAllText
to a file.
The WriteAllText
method will create a new file (or overwrite an existing file) with the contents of the string you pass to it:
public void SaveToFile(string path)
{
try
{
// Create the file, or overwrite if the file exists.
File.WriteAllText(path, this.ToString());
XXXSystem.Log(this.ToString());
}
catch (Exception ex)
{
XXXSystem.Log(
$"An error occurred while saving the configuration file: {ex}";
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论