我无法弄清楚如何让控制台错误检查用户输入然后打开请求的文件。有人能告诉我我做错了吗?
这是我目前的计划。
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 :(得分:2)
此行中有分号
if (!File.Exists(Console.ReadLine())) ;
如果在if
声明之后只有一行,则不会在if
语句中加分号
if (!File.Exists(Console.ReadLine()))
throw new FileNotFoundException();//Check for errors
否则
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
}
}
}
}
答案 1 :(得分: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