簡體   English   中英

程序未寫入文件,但會在C#中寫入控制台

[英]program not writing to file but will write to console in c#

我有一個C#程序,它將不會寫入文件,但會寫入控制台,即使文件寫入行位於控制台之前。 我已經嘗試了幾次修改並通過調試運行,並且它從不寫入文件或僅在文件中放置一行

// Read the file and display it line by line. 
System.IO.StreamReader file = new System.IO.StreamReader("urltest.txt"); 
string myFileName = String.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddhh"), "-urlcheck.log"); 
while((line = file.ReadLine()) != null) 
{
Uri myUri = new Uri(line); 
using (StreamWriter writer = new StreamWriter(myFileName)) 
try
{
// create the web request and response based on the url that has been 
// just read from the file urltest.txt
HttpWebRequest reqFP = (HttpWebRequest)HttpWebRequest.Create(myUri);
HttpWebResponse rspFP = (HttpWebResponse)reqFP.GetResponse();
if (HttpStatusCode.OK == rspFP.StatusCode)
{
// HTTP = 200 - Internet connection available, server online
// Write status of the URL to the log file
writer.WriteLine("=================================================================     =========");
writer.WriteLine("Status code of returned: OK  " + myUri + "  THIS URL IS NOT     BLOCKED!");
Console.WriteLine("Status code of returned: OK  " + myUri + "  THIS URL IS NOT BLOCKED!");
var _uri = myUri.ToString();
string _catstr1 = catURL(_uri);
//regex to get the last 8-9 items of the line and replace them
Regex pat = new Regex(@"</(.*?)a");
string _catstr = pat.Replace(_catstr1, "\x20");
// Write the Catagory of the URL to file and continue
writer.WriteLine("URL " + _catstr);
Console.WriteLine("URL " + _catstr);
}
}

大部分寫入文件的內容都應該在using塊內,或者手動填充並關閉。

using (var writer = ...)
{

    // Do your writing

} // <- upon leaving the using block writer will automatically be cleaned up.

注意:我不是var忠實var但由於我不知道您使用的是什么類,至少可以作為一個有效的代碼示例

您沒有提供用於文件訪問的代碼,但是99%的用戶確保未關閉流。

如果要在關閉編寫器之前強制輸出,請調用Flush()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM