StringBuilder sb = new StringBuilder();我需要不同的void里写入不同的内容在这一个txt中,那么前后两个的stringBuider是否需要修改
时间: 2024-03-24 17:40:55 浏览: 27
如果你需要在同一个文件中写入不同的内容,可以使用同一个 `StringBuilder` 对象,因为 `StringBuilder` 对象可以多次追加内容。在每个 `void` 函数中,你可以将需要写入的内容追加到 `StringBuilder` 对象中,最后再一次性写入文件。示例代码如下:
```c#
private static StringBuilder sb = new StringBuilder();
void WriteErrorTRStationsToTxt1(List<Ty_Monitor> errorStations)
{
foreach (Ty_Monitor station in errorStations)
{
sb.AppendLine(station.Name + "\t" + station.Code + "\t" + station.ErrorTime);
}
}
void WriteErrorTRStationsToTxt2(List<Ty_Monitor> errorStations)
{
foreach (Ty_Monitor station in errorStations)
{
sb.AppendLine(station.Name + "\t" + station.Code + "\t" + station.ErrorTime);
}
}
void SaveToTxtFile(string filePath)
{
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.Write(sb.ToString());
}
}
```
在上面的示例代码中,`WriteErrorTRStationsToTxt1` 和 `WriteErrorTRStationsToTxt2` 函数都将需要写入的内容追加到同一个 `StringBuilder` 对象中。最后,在 `SaveToTxtFile` 函数中,将 `StringBuilder` 对象中的内容写入到指定的文件中。这种方式可以避免在不同的 `void` 函数中重复创建 `StringBuilder` 对象,提高代码的执行效率。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)