[英]Createfile in path given by user only if the file doesn't exist
我僅在以下情況下嘗試創建文件:所定位的路徑中不存在這些文件,並且我猜路徑中的目錄也存在;並且如果該文件已經存在,則不允許用戶繼續使用,因此該應用程序關閉。 我嘗試這樣做,但似乎當我給出位置時會告訴我文件不存在時該文件存在。
this.path = @output;
this.path2File = @output + "\\" + type + "tobearchived.txt";
if (!Directory.Exists(path) && !File.Exists(path2File))
{
File.Create(path2File);
}
else
{
Console.WriteLine("Error: File Already Exists. Press any key to exit.");
Console.ReadKey();
Environment.Exit(0);
}
}
您的IF條件似乎有問題,請嘗試以下操作;
if (Directory.Exists(path) && File.Exists(path2File))
{
Console.WriteLine("Error: File Already Exists. Press any key to exit.");
Console.ReadKey();
Environment.Exit(0);
}
else
{
File.Create(path2File);
}
編輯:您的代碼中的問題是,假設該目錄存在,但文件不存在。 然后'!Directory.Exists(path)'為'false',由於AND條件,它將跳過對'File.Exists(path2File)'的檢查。 因此,控制將直接進入代碼的“其他”部分。
我試過了,對我來說很好。
FileInfo Finfo;
public bool StartLog(string path)
{
Finfo = new FileInfo(path);
if (Finfo.Exists)
{
Finfo.Delete();
FileWriter = Finfo.AppendText();
}
else
{
FileStream fs = Finfo.Create();
fs.Close();
FileWriter = Finfo.AppendText();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.