【发布时间】:2017-05-04 12:24:20
【问题描述】:
目前我正在从我指定的目录 (sourceDirectory) 中获取多个 .txt 文件。我正在生成与 .txt 文件同名的新 .csv 文件 - 每个 .txt 文件一个 .csv 文件。
但是我想在我指定的另一个目录(directoryPath)中生成这些新文件。如果我在初始目录中创建这些文件后运行我的程序,但是如果我再次运行我的程序,它现在会在目标目录中生成文件。
以下是我完成上述内容的代码:
static void Main(string[] args)
{
string sourceDirectory = @"C:directoryWhereTXTFilesAre";
var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt", SearchOption.AllDirectories);
foreach (string currentFile in txtFiles)
{
readFile(currentFile);
}
string directoryPath = @"C:\destinationForCSVFiles";
}
然后我根据原始 .txt 文件创建新的 .csv 文件名,如下所示:
static FileStream CreateFileWithUniqueName(string folder, string fileName, int maxAttempts = 1024)
{
var fileBase = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName);
// build hash set of filenames for performance
var files = new HashSet<string> (Directory.GetFiles(folder));
for (var index = 0; index < maxAttempts; index++)
{
// first try with the original filename, else try incrementally adding an index
var name = (index == 0)
? fileName
: String.Format("{0} ({1}){2}", fileBase, index, ext);
// check if exists
var fullPath = Path.Combine(folder, name);
string CSVfileName = Path.ChangeExtension(fullPath, ".csv");
if (files.Contains(CSVfileName))
continue;
// try to create the file
try
{
return new FileStream(CSVfileName, FileMode.CreateNew, FileAccess.Write);
}
catch (DirectoryNotFoundException) { throw; }
catch (DriveNotFoundException) { throw; }
catch (IOException)
{
}
}
我不明白为什么它最初在 .txt 文件所在的同一目录中创建 .csv 文件,然后在我第二次运行我的代码时它在 directoryPath 中创建它们。
所需的输出:sourceDirectory 保持原样,只有 .txt 文件和 directoryPath 来保存 .csv 文件。
我调用 CreateFileWithUniqueName 的唯一其他地方是在我的 readFile 方法中,代码如下:
using (var stream = CreateFileWithUniqueName(@"C:destinationFilePath", currentFile))
{
Console.WriteLine("Created \"" + stream.Name + "\"");
newFileName = stream.Name;
Globals.CleanedFileName = newFileName;
}
【问题讨论】:
-
但是你没有显示调用CreateFileWithUniqueName的代码请添加
-
@Steve 我已经用代码编辑了问题。
-
你能详细说明一下吗?你的意思是我第一次尝试在 for 循环中使用 fileName 吗?
-
否,评论错误,已删除
-
@Steve 好吧,这肯定是因为我不明白为什么其他任何事情都会影响它
标签: c#