File.Exists - 不想创建新文件

时间:2013-02-04 22:02:37

标签: c#

我是编码的新手 - 所以请耐心等待。我做了很多阅读,无法想出这个。

因此,当您运行我的新应用程序时,您键入文件夹名称。应用程序转到该文件夹​​,然后将扫描此指定文件夹中的2个不同的日志文件。但这里是我遇到麻烦的地方。如果日志不存在 - 它将询问您是否要创建它正在寻找的文件...我不希望它这样做。我只是想去文件夹,如果文件不存在则不做任何事情,继续下一行代码。

这是我到目前为止的代码:

private void btnGo_Click(object sender, EventArgs e)
{
    //get node id from user and build path to logs
    string nodeID = txtNodeID.Text;
    string serverPath = @"\\Jhexas02.phiext.com\rwdata\node\";
    string fullPath = serverPath + nodeID;
    string dbtoolPath = fullPath + "\\DBTool_2013.log";
    string msgErrorPath = fullPath + "\\MsgError.log";

    //check if logs exist
    if (File.Exists(dbtoolPath) == true)
    {
        System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
    }
    {
        MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
    }

应用程序将显示The 2013 DBTool log does not exist for this Node. - 然后它会打开记事本并询问我是否要创建该文件。

Cannot find the \\Jhexas02.phiext.com\rwdata\node\R2379495\DBTool_2013.log file.

Do you want to create a new file?

我不想创建新文件。有什么好方法可以解决这个问题吗?

3 个答案:

答案 0 :(得分:4)

你在“if”之后跳过了“Else”

if (File.Exists(dbtoolPath) == true)
            {
                System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
            }
            else
            {
                MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
            }

答案 1 :(得分:1)

当您的代码编译时(仅添加类似的支持是有效的),可以像在else语句中添加if一样简单:

if (File.Exists(dbtoolPath) == true) // This line could be changed to: if (File.Exists(dbtoolPath))
{
    System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
}
else // Add this line.
{
    MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
}

正如您现在的代码所示,此部分将始终运行:

{
    MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
}

它与此代码基本相同:

if (File.Exists(dbtoolPath) == true)
{
    System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
}

MessageBox.Show("The 2013 DBTool log does not exist for this Node.");

答案 2 :(得分:1)

试试这个:

if (File.Exists(dbtoolPath))
    {
        System.Diagnostics.Process.Start("notepad.exe", dbtoolPath);
    }
else {
        MessageBox.Show("The 2013 DBTool log does not exist for this Node.");
    }