[英]C# - How to Stop StreamWriter Writing Blank Line at the End of a File?
我搜索了许多 web 页面,但我似乎找不到任何地方显示如何在使用 StreamWriter 时停止出现在文件末尾的空行。
我在下面编写的代码是我可以让它为我工作的唯一方法。虽然这对于我正在创建的实用程序来说非常有效,但我想知道是否有更好/更有效的方法来做这个?
int count = 0;
int lineCount = newFile.Count;
using (System.IO.StreamWriter extract = new System.IO.StreamWriter(outputFile, true))
{
foreach (var line in newFile)
{
count++;
if (count != lineCount)
{
extract.Write(line + Environment.NewLine);
}
else
{
extract.Write(line);
}
}
}
有什么想法的人吗?
由于您正在访问Count
属性,这意味着您的newFile
源实现了IList
接口。 这意味着您可以通过它的索引来访问它。
使用for
循环而不是foreach
:
for (int i = 0; i < newFile.Count - 1; i++)
{
extract.WriteLine(newFile[i]);
}
extract.Write(newFile[newFile.Count - 1]);
检查这个...
var values = Enumerable.Range(1,10);
var output = string.Format(string.Join(",{0}", values), Environment.NewLine);
File.WriteAllText(path, output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.