自动生成新文件时如何避免重复文件(不同扩展名)

时间:2017-04-06 11:21:14

标签: c#

我创建了一个清除访问和错误日​​志的程序,然后将它们输出到同一目录中的新文件中。输入格式为.txt,输出格式为.csv - 但它给我两个输出文件,一个是.csv格式,一个是.txt格式(.txt文件是空的)而不是.csv文件?我无法理解为什么会这样。 以下是目录中显示的两个输出文件:

The two files generated from the code:

以下是生成具有唯一名称的新文件的代码:

 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);
             if(files.Contains(fullPath))
                continue;

            // try to create the file
            try
            {
                 return new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write);
            }
            catch (DirectoryNotFoundException) { throw; }
            catch (DriveNotFoundException) { throw; }
            catch (IOException) 
            {

            }
          }
    throw new Exception("Could not create unique filename in " + maxAttempts + " attempts");
       }

最后,下面的代码是读取现有文件并清除它的代码:

public static void readFile(string fileName)
    {
        using (var stream = CreateFileWithUniqueName(@"C:\Users\michael\Desktop\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\", fileName))
        {
            Console.WriteLine("Created \"" + stream.Name + "\"");

            newFileName = stream.Name;
            Globals.CleanedErrorFileName = newFileName;
        }

        string CSVfileName = Path.ChangeExtension(newFileName, ".csv");
        StreamReader reader = new StreamReader(fileName);
        StreamWriter writer = new StreamWriter(CSVfileName);
        string line;

        string personalIdentifier = new string(fileName.Take(4).ToArray());
        string gender = fileName.Substring(fileName.Length - 5, 1);
        string classification = fileName.Substring(fileName.Length - 8, 2);
        string text = string.Empty; 

        while ((line = reader.ReadLine()) != null)
        {
            string[] cleanArray;
            cleanArray = new string[5];

            var result = line.Split('[')
                 .Select((element, index) => index % 2 == 0
                  ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                  : new string[] { element })
                 .SelectMany(element => element).ToList();

            cleanArray[0] = personalIdentifier;
            cleanArray[1] = gender;
            cleanArray[2] = classification;
            cleanArray[3] = result[0];
            cleanArray[4] = result[2];

            cleanArray[4] = cleanArray[4].Substring(7);
            cleanArray[4] = cleanArray[4].Replace("]", " ");
            cleanArray[4] = cleanArray[4].Insert(15, ",");

            cleanArray[3] = cleanArray[3].Remove(cleanArray[3].Length - 2);

            cleanArray[4] = cleanArray[4].Substring(0, cleanArray[4].IndexOf(":") + 1); 

            //re-formatting the date so that it can be accepted by machine learning
            var dateString = cleanArray[3];
            var date = DateTime.ParseExact(dateString, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.InvariantCulture);
            var newDateString = date.ToString("yyyy-MM-dd HH:mm:ss");

            //inserting the new date and time into the array
            cleanArray[3] = newDateString;

            //push each clean array onto the file that has been automatically created at the top
            writer.WriteLine(string.Join(", ", cleanArray.Select(v => v.ToString())));
            writer.WriteLine();
        }

我希望这个问题很小但我似乎无法找到它! 在此先感谢!!

1 个答案:

答案 0 :(得分:3)

这条线是罪魁祸首:

return new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write);

此时,fullPath中的文件名仍具有.txt扩展名,这将创建空的.txt文件。然后将扩展名更改为.csv并执行此操作:

StreamWriter writer = new StreamWriter(CSVfileName);

创建新的.csv文件

此外,您的代码中的两个流都不会关闭。