我循环遍历目录并获取文件 在循环时,我使用StreamWriter将文件的完整路径名称写入文件 我的问题是我必须控制文件的大小 - 它不能超过60K
我该如何做到这一点?
我尝试在循环中间更改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;
}
}
}
任何帮助将不胜感激 我很乐意接受任何改进的想法
由于 大卫
答案 0 :(得分:2)
尝试将代码更改为:
if (myPaths.Length >= 60000)
{
myStream.Close();
outFile = "c:\\dirA\\GS_dirData_" + (FileCounter += 1).ToString() + ".txt";
myStream = new StreamWriter(outFile);
}
您正在if语句中创建一个本地范围的变量。您需要将新的StreamWriter设置为函数作用域myStream。