Как открыть файл .txt с использованием openFileDialog в C #? - PullRequest
3 голосов
/ 12 июня 2011

Мне нужно открыть и прочитать файл .txt, вот код, который я использую:

Stream myStream;
openFileDialog1.FileName = string.Empty; 
openFileDialog1.InitialDirectory = "F:\\";
if (openFileDialog1.ShowDialog() == DialogResult.OK) 
{
    var compareType = StringComparison.InvariantCultureIgnoreCase;
    var fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
    var extension = Path.GetExtension(openFileDialog1.FileName);
    if (extension.Equals(".txt", compareType))
    {
        try 
        { 
            using (myStream = openFileDialog1.OpenFile()) 
            { 
                string file = Path.GetFileName(openFileDialog1.FileName);
                string path = Path.GetFullPath(file); //when i did it like this it's work fine but all the time give me same path whatever where my "*.txt" file is
                //Insert code to read the stream here. 
                //fileName = openFileDialog1.FileName; 
                StreamReader reader = new StreamReader(path);
                MessageBox.Show(file, "fileName");
                MessageBox.Show(path, "Directory");
            } 
        } 
        // Exception thrown: Empty path name is not legal
        catch (ArgumentException ex) 
        { 
            MessageBox.Show("Error: Could not read file from disk. " +
                            "Original error: " + ex.Message); 
        } 
    }
    else 
    {
        MessageBox.Show("Invaild File Type Selected");
    } 
} 

Приведенный выше код вызывает исключение, которое говорит "Пустое имя путине законно ".

Что я делаю не так?

Ответы [ 4 ]

7 голосов
/ 12 июня 2011

Как указано hmemcpy , ваша проблема в следующих строках

using (myStream = openFileDialog1.OpenFile())
{
   string file = Path.GetFileName(openFileDialog1.FileName);
   string path = Path.GetDirectoryName(file);
   StreamReader reader = new StreamReader(path);
   MessageBox.Show(file, "fileName");
   MessageBox.Show(path, "Directory");
} 

Я сломаюсь за тебя:

/*
 * Opend the file selected by the user (for instance, 'C:\user\someFile.txt'), 
 * creating a FileStream
 */
using (myStream = openFileDialog1.OpenFile())
{
   /*
    * Gets the name of the the selected by the user: 'someFile.txt'
    */
   string file = Path.GetFileName(openFileDialog1.FileName);

   /*
    * Gets the path of the above file: ''
    *
    * That's because the above line gets the name of the file without any path.
    * If there is no path, there is nothing for the line below to return
    */
   string path = Path.GetDirectoryName(file);

   /*
    * Try to open a reader for the above bar: Exception!
    */
   StreamReader reader = new StreamReader(path);

   MessageBox.Show(file, "fileName");
   MessageBox.Show(path, "Directory");
} 

Что вам нужно сделать, это изменить код на что-то вроде

using (myStream = openFileDialog1.OpenFile())
{
   // ...
   var reader = new StreamReader(myStream);
   // ...
}
6 голосов
/ 12 июня 2011

Вы хотите, чтобы пользователь выбирал только .txt файлы? Затем используйте свойство .Filter , например:

openFileDialog1.Filter = "txt files (*.txt)|*.txt";
5 голосов
/ 12 июня 2011

Ваша ошибка в строках:

string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(file);

В первой строке переменная file будет содержать только имя файла, например, MyFile.txt, поэтому вторая строка возвращает пустую строкуpath переменная.Далее в вашем коде вы попытаетесь создать StreamReader с пустым путем, и это то, что вызывает исключение.

Кстати, это именно то, что говорит вам исключение.Если вы удалите try..catch вокруг блока using, вы увидите, что это произошло во время отладки в вашей Visual Studio.

1 голос
/ 16 августа 2013

StreamReader принимает тип объекта Stream, когда вы передаете ему строку. попробуйте это,

Stream myStream;

        using (myStream = openFileDialog1.OpenFile())
        {
            string file = Path.GetFileName(openFileDialog1.FileName);
            string file2 = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);

            string path = Path.GetDirectoryName(openFileDialog1.FileName);

            StreamReader reader = new StreamReader(myStream);

            while (!reader.EndOfStream)
            {
                MessageBox.Show(reader.ReadLine());
            }

            MessageBox.Show(openFileDialog1.FileName.ToString());
            MessageBox.Show(file, "fileName");
            MessageBox.Show(path, "Directory");
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...