无法将字符串转换为system.io

时间:2019-04-23 09:44:16

标签: c#

我正在尝试让我的文件流读取用户选择的任何文本文件。选择文件路径后,文件路径将显示在文本框中。

我想使用此文件路径,以便我的流阅读器知道要读取的文件。

“ Stream fileStream = FilePath.Text;”不起作用。

public void ValidateButton_Click(object sender, EventArgs e)

        {
            {


                List<string> temp = new List<string>();
                string[] finalArray;

                Stream fileStream = FilePath.Text;
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    // We read the file then we split it.
                    string lines = reader.ReadToEnd();
                    string[] splittedArray = lines.Split(',');

                    // We will check here if any of the strings is empty (or just whitespace).
                    foreach (string currentString in splittedArray)
                    {
                        if (currentString.Trim() != "")
                        {
                            // If the string is not empty then we add to our temporary list.
                            temp.Add(currentString);
                        }
                    }

                    // We have our splitted strings in temp List.
                    // If you need an array instead of List, you can use ToArray().
                    finalArray = temp.ToArray();
 }
}

我收到错误,无法将字符串转换为system.io。

如何让流阅读器从“ FilePath”文本框中读取所选文件

2 个答案:

答案 0 :(得分:2)

FilePath.Text返回一个字符串,该字符串是文件在驱动器上的位置

下面的代码可以工作

using (StreamReader reader = new StreamReader(FilePath.Text))
{
    // We read the file then we split it.
    string lines = reader.ReadToEnd();
    string[] splittedArray = lines.Split(',');

    // We will check here if any of the strings is empty (or just whitespace).
    foreach (string currentString in splittedArray)
    {
        if (currentString.Trim() != "")
        {
            // If the string is not empty then we add to our temporary list.
            temp.Add(currentString);
        }
    }

    // We have our splitted strings in temp List.
    // If you need an array instead of List, you can use ToArray().
    finalArray = temp.ToArray();
}

答案 1 :(得分:1)

使用StreamReader构造函数的overload接受路径

using (StreamReader reader = new StreamReader(FilePath.Text))