[英]Creating unique files in another directory
目前我從我指定的目錄(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;
}
您似乎正在傳遞源文件的完整文件名。 這會混淆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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.