0

我有一个 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);
}
}
4

3 回答 3

2

大多数写出文件的东西都应该在一个using块内或手动刷新和关闭。

using (var writer = ...)
{

    // Do your writing

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

注意:我不是一个超级粉丝,var但因为我不知道你正在使用什么类,它至少是一个有效的代码示例

于 2013-06-20T17:26:17.530 回答
1

您没有提供文件访问的代码,但 99% 确定您没有关闭流。

于 2013-06-20T17:32:20.410 回答
0

Flush()如果您想在关闭作家之前强制输出,请致电

于 2013-06-20T17:21:39.523 回答