猿问

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

我试图让我的文件流读取用户选择的任何文本文件。文件路径将在他们选择后出现在文本框中。


我想使用这个文件路径,以便我的 streamreader 知道要读取什么文件。


"流 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。


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


Qyouu
浏览 151回答 2
2回答

子衿沉夜

FilePath.Text返回一个字符串,它是驱动器上文件的位置下面的代码可以工作using (StreamReader reader = new StreamReader(FilePath.Text)){&nbsp; &nbsp; // We read the file then we split it.&nbsp; &nbsp; string lines = reader.ReadToEnd();&nbsp; &nbsp; string[] splittedArray = lines.Split(',');&nbsp; &nbsp; // We will check here if any of the strings is empty (or just whitespace).&nbsp; &nbsp; foreach (string currentString in splittedArray)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (currentString.Trim() != "")&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // If the string is not empty then we add to our temporary list.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp.Add(currentString);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // We have our splitted strings in temp List.&nbsp; &nbsp; // If you need an array instead of List, you can use ToArray().&nbsp; &nbsp; finalArray = temp.ToArray();}

料青山看我应如是

使用接受路径的构造函数的重载StreamReaderusing&nbsp;(StreamReader&nbsp;reader&nbsp;=&nbsp;new&nbsp;StreamReader(FilePath.Text))
随时随地看视频慕课网APP
我要回答