2015-10-30 47 views
1

我正在创建一个小型的C#程序,该程序从用户选择的位置读取纺织品..我设法正确地读取了这些文件,但是我想如果错误地输入文件名/路径....或文件类型不正确,则向用户显示错误消息。 我已经尝试了有限的知识内的一切,现在我有点卡住了。任何帮助都将非常感激。由于检查用户是否输入了正确的文件系统路径

using System; 

class ReadFromFile 
{ 
static void Main() 
{ 
    Console.WriteLine ("Welcome to Decrypter (Press any key to    begin)"); 
    Console.ReadKey(); 

    //User selects file they wish to decrypt 
    int counter = 0; 
    string line; 
    string path; 


    Console.WriteLine ("\nPlease type the path to your file"); 
    path = Console.ReadLine(); 

    // Read the file and display it line by line. 
    System.IO.StreamReader file = 
     new System.IO.StreamReader (path); 

     while ((line = file.ReadLine()) != null) { 

      Console.WriteLine (line); 
      counter++; 
     } 

     file.Close(); 

     // Suspend the screen. 
     Console.ReadLine(); 
     } 
     } 
+2

如果您只想查看路径是否有效以及文件是否存在,可以使用['File.Exists'](https://msdn.microsoft.com/zh-cn/library/system.io .file.exists(v = vs.110).aspx) – juharr

回答

1

使用

try 
{ 
    if (!File.Exists(path)) 
    { 
     // Tell the user 
    } 
} 
catch (Exception ex) 
{ 
    // tell the user 
} 

文件的存在

添加

using System.IO; 

代码文件的顶部

+1

Althoug如果使用IO-方法,使用'Try ... Catch'可能会很有用,在这种情况下它看起来很重要。但事实并非如此。实际上,如果路径无效,'File.Exists'没有问题。 –

+0

@TimSchmelter,你是对的,它可能是过度杀伤,因为它似乎'File.Exists'不会抛出异常,即使当'path'为空或否则无效或该文件是不可访问的。 – GreatAndPowerfulOz

+0

将是一个奇怪的方法,用于检查您是否提供有效的路径,但如果该验证返回“false”,则会引发异常。那么'bool'返回值的目的是什么? –

1

使用此:

bool exists = System.IO.File.Exists(path); 
相关问题