0

私は C# プログラムを持っていますが、ファイルへの書き込み行がコンソールの前にあるにもかかわらず、ファイルに書き込みませんが、コンソールに書き込みます。私はいくつかの変更を試み、デバッグも実行しましたが、ファイルに書き込まないか、ファイルに1行しか入れません

// 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 に答える