首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >程序不写入文件,但将写入c#中的控制台

程序不写入文件,但将写入c#中的控制台
EN

Stack Overflow用户
提问于 2013-06-21 01:20:00
回答 3查看 130关注 0票数 0

我有一个C#程序,它不会写入文件,但会写入控制台,即使文件写入行在控制台之前。我尝试了几次修改,也运行了debug,但它从不写入文件,或者只在文件中放入一行

代码语言:javascript
复制
// 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);
}
}
EN

回答 3

Stack Overflow用户

发布于 2013-06-21 01:26:18

大多数写入文件的内容都应该在using块中,或者手动刷新并关闭。

代码语言:javascript
复制
using (var writer = ...)
{

    // Do your writing

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

注意:我不是var的狂热粉丝,但由于我不知道您使用的是哪个类,因此它至少是一个有效的代码示例

票数 2
EN

Stack Overflow用户

发布于 2013-06-21 01:32:20

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

票数 1
EN

Stack Overflow用户

发布于 2013-06-21 01:21:40

如果要在关闭写入器之前强制输出,请调用Flush()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17219880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档