我有这个代码:
private void SearchForDoc()
{
try
{
outputtext = @"c:\temp\outputtxt";
outputphotos = @"c:\temp\outputphotos";
temptxt = @"c:\temp\txtfiles";
tempphotos = @"c:\temp\photosfiles";
if (!Directory.Exists(temptxt))
{
Directory.CreateDirectory(temptxt);
}
if (!Directory.Exists(tempphotos))
{
Directory.CreateDirectory(tempphotos);
}
if (!Directory.Exists(outputtext))
{
Directory.CreateDirectory(outputtext);
}
if (!Directory.Exists(outputphotos))
{
Directory.CreateDirectory(outputphotos);
}
t = Environment.GetEnvironmentVariable(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
ApplyAllFiles(t, ProcessFile);
for (int i = 0; i < textfiles.Length; i++)
{
FileInfo fi = new FileInfo((textfiles[i]));
DirectoryInfo d = new DirectoryInfo(temptxt);
long dirSize = DirSize(d);
if ((dirSize + fi.Length) <= 8388608)
fi.CopyTo(temptxt + "\\" + fi.Name, true);
else
break;
}
Compressions("textfiles.zip", temptxt, outputtext);
问题出在这部分:
for (int i = 0; i < textfiles.Length; i++)
textfiles
是string[]
但现在textfiles
不再存在,因为我正在使用以下ApplyAllFiles
方法:
static void ProcessFile(string path) {/* ... */}
static void ApplyAllFiles(string folder, Action<string> fileAction)
{
foreach (string file in Directory.GetFiles(folder))
{
fileAction(file);
}
foreach (string subDir in Directory.GetDirectories(folder))
{
try
{
ApplyAllFiles(subDir, fileAction);
}
catch
{
// swallow, log, whatever
}
}
}
编辑**
在我的方法中,我现在有:
string t = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string[] textfiles = ApplyAllFiles(t, "*.txt", ProcessFile).ToArray();
然后是 ApplyAllFiles 方法:
static void ProcessFile(string path) {/* ... */}
static IEnumerable<string> ApplyAllFiles(string folder, string searchPattern, Action<string> fileAction)
{
foreach (string file in Directory.GetFiles(folder))
{
fileAction(file);
yield return file;
}
foreach (string subDir in Directory.GetDirectories(folder, searchPattern))
{
// try
//{
foreach (string file in ApplyAllFiles(subDir, searchPattern, fileAction))
{
yield return file;
}
// }
// catch
// {
// swallow, log, whatever
// }
}
}
必须在 catch 中删除 try 产量不能在 try 和 catch 第二我在第二个内部 foreach 循环中也添加了 searchPatterns 变量
结果是我只得到 pdf 或其他文件,而不是大约 25 个文件的文本,并且只能从主文件目录中获取。