![](/img/trans.png)
[英]C# - How to Stop StreamWriter Writing Blank Line at the End of a File?
[英]Destination file blank after writing with StreamWriter C#
我編寫了一個控制台應用程序,它本身可以正常運行。 它的主要輸出在控制台中效果很好。 但是循環內的結果我想寫入文本文件。 我使用StreamWriter嘗試了此操作,盡管在編譯或運行時未收到任何錯誤,但C:驅動器中的文件仍為空白。 有人可以發現我錯過的任何愚蠢或快速的事情嗎?
如果可以幫助,請提前謝謝。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test2
{
class Program
{
static void Main(string[] args)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\Test.txt");
double z = 0;
double x = 1;
double y = 1;
Console.WriteLine("How many lines should be written to the file?");
Console.WriteLine();
z = double.Parse(System.Console.ReadLine());
Console.WriteLine("Writing " + z + "lines to file!");
Console.WriteLine();
while (z > 0)
{
y = Math.Pow(x, 2);
Console.WriteLine(x + ", " + y*10);
file.WriteLine(x + ", " + y*10);
z = z - 1;
x = x + 1;
}
Console.WriteLine();
Console.WriteLine("**Generation Complete**");
Console.WriteLine();
Console.WriteLine("-------------------------------");
Console.WriteLine();
Console.WriteLine("**Writing to file successful**");
Console.WriteLine();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
file.Close();
}
}
}
我以前遇到過類似的問題。 如果我沒記錯的話,解決方案歸結為將StreamWriter包裝在using塊中,而不是創建它然后嘗試關閉它,例如
static void Main(string[] args)
{
using (var file = new System.IO.StreamWriter("c:\\Test.txt"))
{
double z = 0;
double x = 1;
double y = 1;
Console.WriteLine("How many lines should be written to the file?");
Console.WriteLine();
z = double.Parse(System.Console.ReadLine());
Console.WriteLine("Writing " + z + "lines to file!");
Console.WriteLine();
while (z > 0)
{
y = Math.Pow(x, 2);
Console.WriteLine(x + ", " + y*10);
file.WriteLine(x + ", " + y*10);
z = z - 1;
x = x + 1;
}
Console.WriteLine();
Console.WriteLine("**Generation Complete**");
Console.WriteLine();
Console.WriteLine("-------------------------------");
Console.WriteLine();
Console.WriteLine("**Writing to file successful**");
Console.WriteLine();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
對於所有實現IDisposable
事物(如StreamWriter
,都使用using
語句。 這將確保處置非托管資源( 即使出錯 )。 如果AutoFlush
屬性為false
(默認值),它還將刷新流。
using(var file = new System.IO.StreamWriter("c:\\Test.txt"))
{
// ...
file.WriteLine(x + ", " + y*10);
// rest of code here ...
}
當我運行該代碼時,我看到一個異常:
Unhandled Exception: System.UnauthorizedAccessException:
Access to the path 'c:\Test.txt' is denied.
目前尚不清楚您如何運行它,但是如果將其配置為控制台應用程序並且您從控制台窗口運行它,那么您肯定會看到任何異常,我懷疑您會看到相同的東西。
嘗試將其更改為寫入您絕對有權訪問的位置-並嘗試找出為什么以前沒有看到異常。
另外,最好使用using
語句,如其他答案所示-但這不能解釋沒有創建文件就干凈運行的情況(無例外)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.