打开文件对话框中的strFileName

时间:2012-11-02 22:20:30

标签: c# openfiledialog

我对c#相当新。

我的问题是打开文件对话框中的strFileName是什么?

我目前有这个代码:

 string input = string.Empty;

        OpenFileDialog open = new OpenFileDialog();

        open.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.* ";

        open.InitialDirectory = "C:";

        if (open.ShowDialog() == DialogResult.OK)

            strFileName = open.FileName;

        if (strFileName == String.Empty)

            return; 

它会在strFileName上出现错误。我无法找到解释它在此代码中的作用。

任何帮助将不胜感激,如果以前曾询问过这个问题我会道歉。

4 个答案:

答案 0 :(得分:3)

在不知道错误是什么的情况下,只需查看代码,就可能在strFileName上遇到编译错误,因为它未声明:

您可以将代码更改为:

string input = string.Empty;

OpenFileDialog open = new OpenFileDialog();

open.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.* ";

open.InitialDirectory = "C:";

if (open.ShowDialog() == DialogResult.OK)

   input = open.FileName;

if (input == String.Empty)

   return; 

或者这个:

string strFileName = string.Empty;

OpenFileDialog open = new OpenFileDialog();

open.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.* ";

open.InitialDirectory = "C:";

if (open.ShowDialog() == DialogResult.OK)

   strFileName = open.FileName;

if (strFileName == String.Empty)

   return; 

答案 1 :(得分:1)

它没有给我一个错误 - 虽然我必须声明它。你呢?

    string strFileName = "";  // added this line - it compiles and runs ok

    private void TestFunc()
    {
        string input = string.Empty;

        OpenFileDialog open = new OpenFileDialog();

        open.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.* ";

        open.InitialDirectory = "C:";

        if (open.ShowDialog() == DialogResult.OK)

            strFileName = open.FileName;

        if (strFileName == String.Empty)

            return;
    }

答案 2 :(得分:1)

你需要先声明strFileName

string strFileName = string.empty();

然后使用它。

答案 3 :(得分:1)

您需要将变量strFilename声明为字符串:

string strFileName = string.Empty;
OpenFileDialog open = new OpenFileDialog();
open.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.* ";
open.InitialDirectory = "C:";
if (open.ShowDialog() == DialogResult.OK)
{
    strFileName = open.FileName;
} 
/* you probably don't want this unless it's part of a larger block of code
if (strFileName == String.Empty)
{
    return; 
}
*/

return strFileName;