【问题标题】:Creating unique files in another directory在另一个目录中创建唯一文件
【发布时间】: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#


【解决方案1】:

您似乎传递了源文件的完整文件名。这会使 CreateFileWithUniqueFilename 中的 Path.Combine 感到困惑,因为您陷入了在 Path.Combine 的文档中找到的这种微妙的评论中

paths 应该是要组合的路径部分的数组。如果 后续路径之一是绝对路径,然后组合 操作从该绝对路径开始重置,丢弃所有 以前的组合路径。

你可以很容易地修复它

 using (var stream = CreateFileWithUniqueName(@"C:\destinationFilePath",  
                                        Path.GetFileName(currentFile)))
 {
      Console.WriteLine("Created \"" + stream.Name + "\"");
      newFileName = stream.Name;
      Globals.CleanedFileName = newFileName;
}

或者最好在 CreateFileWithUniqueName 中提取没有路径的文件名

static FileStream CreateFileWithUniqueName(string folder, string fileName, int maxAttempts = 1024)
{
    var fileBase = Path.GetFileName(fileName);
    fileBase = Path.GetFileNameWithoutExtension(fileBase);
    var ext = Path.GetExtension(fileBase);

另外,您应该使用清理后的文件名构建您的 CSVfileName

    var name = (index == 0)
        ? String.Format("{0}{1}", fileBase, ext);
        : String.Format("{0} ({1}){2}", fileBase, index, ext);
    var fullPath = Path.Combine(folder, name);
    string CSVfileName = Path.ChangeExtension(fullPath, ".csv");
    if (files.Contains(CSVfileName))
        continue;

【讨论】:

  • 两次定义fileBase?你的意思是定义别的东西吗?
  • 如果没有 VS 看护你的代码,复制/粘贴是很困难的。
  • 没问题,我很高兴能帮助像你这样努力理解自己的代码的人在 SO 上再见
猜你喜欢
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 2014-04-26
  • 1970-01-01
  • 2012-02-03
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多