2

我对 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

4 回答 4

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; 
于 2012-11-02T22:27:27.677 回答
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;
    }
于 2012-11-02T22:27:01.403 回答
1

你需要先声明 strFileName

string strFileName = string.empty();

然后使用它。

于 2012-11-02T22:27:35.100 回答
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;
于 2012-11-02T22:28:01.980 回答