我正在循環目錄並獲取文件 循環時,我正在使用StreamWriter將文件的完整路徑名寫入文件 我的問題是我必須控制文件的大小 - 它不能超過60KC# - 寫入時檢查文件大小 - 更改中間文件
我該如何做到這一點?
我試圖在循環這樣的中途改變的StreamWriter:
if (myPaths.Length >= 60000)
{
outFile = "c:\\tag\\GS_dirData_" + (FileCounter += 1).ToString() + ".txt";
StreamWriter myStream = new StreamWriter(outFile);
}
但我得到一個錯誤的警告,我不能這樣做
這裏是我的全碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using Microsoft.Win32;
using System.Globalization;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo("c:/myDir/");
string outputFile = "c:\\dirA\\PathsFile.txt";
StreamWriter sw = new StreamWriter(outputFile);
string doneFile = "c:\\dirA\\ConfirmComplete.txt";
if (File.Exists(doneFile)) File.Delete(doneFile);
int ct = 0;
ct = getAllFiles(di, "*.i", sw, outputFile);
StreamWriter myDoneFile = new StreamWriter(doneFile);
myDoneFile.AutoFlush = true;
myDoneFile.WriteLine("Done");
myDoneFile.WriteLine("Processed " + ct.ToString() + " files");
myDoneFile.WriteLine("File Size = "+outputFile.Length.ToString());
}
static int getAllFiles(DirectoryInfo dir, string searchPattern, StreamWriter myStream, string outFile)
{
var directories = dir.GetFiles(searchPattern, SearchOption.AllDirectories);
int counter = 0;
int FileCounter = 1;
foreach (var file in directories)
{
if (file.FullName.Contains("\\BAK\\")) continue;
myStream.WriteLine(file.FullName);
counter += 1;
FileInfo myPaths = new FileInfo(outFile);
if (myPaths.Length >= 60000)
{
myStream.Close();
outFile = "c:\\dirA\\GS_dirData_" + (FileCounter += 1).ToString() + ".txt";
StreamWriter myStream = new StreamWriter(outFile);
}
}
return counter;
}
}
}
任何幫助,將不勝感激 我很樂意接受任何增強思想
感謝 大衛
究竟是什麼錯誤? – clcto
您正在循環中創建本地StreamWriter。我不認爲你想這樣做。您正在關閉outerstream,然後打開一個新的但不是相同的myStream變量。你正在向當地開放。 – pstrjds