2015-07-01 62 views
1

我无法弄清楚如何让控制台错误检查用户输入,然后打开请求的文件。有人能告诉我我做错了什么吗?C#打开带有错误信息的变量文件

这是我目前的程序。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.IO; 

namespace ConsoleApplication5 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     while (true) 
     { 
      Console.WriteLine(">Enter File to open.");//Prompt user for file name 

      try 
      { 
       if (!File.Exists(Console.ReadLine())) 
       throw new FileNotFoundException();//Check for errors 

      } 
      catch (FileNotFoundException) 
      { 
       Console.WriteLine("You stuffed up!"); //Display error message 
      } 
     } 
      System.Diagnostics.Process.Start(@Console.ReadLine()); //set valid reply response 
      Console.ReadLine(); 
     } 


    } 
} 
+0

你有一个无限循环,而(真){}这将永远不会结束,无论你输入给。代码System.Diagnostics.Process.Start(@ Console.ReadLine());无法达到。如果找到该文件,则可以打开该循环。 – keerthee

回答

2

你在这一行有一个分号 if (!File.Exists(Console.ReadLine())) ;

你不把分号上if语句,如果只您if声明以下后有一行是罚款

if (!File.Exists(Console.ReadLine())) 
       throw new FileNotFoundException();//Check for errors 

else

if (!File.Exists(Console.ReadLine())){ 
       throw new FileNotFoundException();//Check for errors 

//some more code 
} 

编辑:

class Program 
{ 
    static void Main(string[] args) 
    { 
     while (true) 
     { 
      Console.WriteLine(">Enter File to open.");//Prompt user for file name 
      string s = Console.ReadLine(); 
      try 
      { 
       if (!File.Exists(s)) 
        throw new FileNotFoundException();//Check for errors 
       else 
        System.Diagnostics.Process.Start(s); //set valid reply response 

       Console.ReadLine(); 
      } 
      catch (FileNotFoundException) 
      { 
       Console.WriteLine("You stuffed up!"); //Display error message 
      } 
     } 
    } 
} 
+0

只需修复它,它仍然不会打开我输入到控制台中的文件。有任何想法吗? –

+0

@JordanSlack请参阅编辑。基本上这条线是无法访问的'System.Diagnostics.Process.Start(@ Console.ReadLine());',将其移动到'try'块中。 – jmc

+0

谢谢你,我已经坚持了几个小时。 –

0
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.IO; 
namespace ABCD 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      while (true) 
      { 
       Console.WriteLine(">Enter File to open.");//Prompt user for file name 
       string fileName = Console.ReadLine(); 
       try 
       { 
        if (!File.Exists(fileName)) 
         throw new FileNotFoundException();//Check for errors 
        else 
         System.Diagnostics.Process.Start(fileName); //set valid reply response 

        Console.ReadLine(); 
       } 
       catch (FileNotFoundException) 
       { 
        Console.WriteLine("You stuffed up!"); //Display error message 
       } 
      } 
     } 
    } 
} 

只是确保你做文件名即可执行文件与输入“.EXE”扩展,并确保你提供完整路径。

即作出这样的输入 “C:\ Program Files文件\的Internet Explorer \ IEXPLORE.EXE”,以打开Internet Explorer