2016-06-10 2 views
0

파일이 경로에 존재하지 않고 해당 경로가 존재하는 것으로 간주하고 파일이 존재하는 경우에만 파일을 만들려고합니다. 이미 존재하므로 사용자가 계속해서 앱을 종료하지 못하게합니다. 나는이 일을 시도했으나 위치를 알려줄 때 파일이 존재하지 않는다고 알려줍니다.파일이 존재하지 않는 경우에만 사용자가 지정한 경로의 파일 생성

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); 
     } 
    } 

답변

1

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'이고 조건으로 인해 'File.Exists (path2File)'에 대한 검사를 건너 뜁니다. 따라서 컨트롤은 코드의 'else'부분으로 직접 이동합니다.

+0

나는 내 논리를 엉망으로 만들었습니다. 많은 사람 – PhillipsJP

0

나는 이것을 시도하고 나를 위해 잘 작동했다.

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(); 
     } 
} 
관련 문제