[英]program not writing to file but will write to console in c#
I have a C# program and it will not write to a file but does write to console, even though the file write line is before console. 我有一个C#程序,它将不会写入文件,但会写入控制台,即使文件写入行位于控制台之前。 i have tried several modifications and run through debug as well, and it never writes to the file or it puts one line in the file only
我已经尝试了几次修改并通过调试运行,并且它从不写入文件或仅在文件中放置一行
// 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);
}
}
Most anything that writes out to a file should be either within a using
block or manually fushed and closed. 大部分写入文件的内容都应该在
using
块内,或者手动填充并关闭。
using (var writer = ...)
{
// Do your writing
} // <- upon leaving the using block writer will automatically be cleaned up.
Note: I'm not a huge fan of var
but as I don't know what class you're using it at least makes a valid example of code 注意:我不是
var
忠实var
但由于我不知道您使用的是什么类,至少可以作为一个有效的代码示例
您没有提供用于文件访问的代码,但是99%的用户确保未关闭流。
如果要在关闭编写器之前强制输出,请调用Flush()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.