gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:00:37 26 4
gpt4 key购买 nike

我创建了一个程序来清理访问和错误日​​志,然后将它们输出到同一目录中的新文件中。输入格式为 .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();
}

我希望问题很小,但我似乎找不到它!提前致谢!!

最佳答案

这一行是罪魁祸首:

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

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

StreamWriter writer = new StreamWriter(CSVfileName);

创建新的 .csv 文件

此外,这两个流在您的代码中永远不会关闭。

关于c# - 自动生成新文件时如何避免重复文件(不同扩展名),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43253715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com