Zbone
Zbone

Reputation: 507

Streamreader problems

I'm a real noob to C# trying to write a small XML replacer program based on a short code a friend of mine used in one of his apps..

I'm having trouble with this line:

StreamReader sr = new StreamReader(textBox1.Text);

I get an error: "Empty path name is not legal." why doesn't this work?

the code is:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ReplaceMe
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        StreamReader sr = new StreamReader(textBox1.Text);
        StreamWriter sw = new StreamWriter(textBox1.Text.Replace(".", "_new."));
        string cur = "";
        do
        {
            cur = sr.ReadLine();
            cur = cur.Replace(textBox2.Text, textBox3.Text);
            sw.WriteLine(cur);
        }
        while (!sr.EndOfStream);

        sw.Close();
        sr.Close();

        MessageBox.Show("Finished, the new file is in the same directory as the old one");
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }


    private void button1_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            this.textBox1.Text = openFileDialog1.FileName;
        }

    }


}
}

Thanks in advance :)

Upvotes: 2

Views: 692

Answers (4)

Kakashi
Kakashi

Reputation: 2195

it's because you're setting an empty string in StreamReader constructor.

I recommend you do a simple validation before read file.

as this:

 string fileName = textBox1.Text; 
    if(String.IsNullOrEmpty(fileName)) {
       //textbox is empty 
    } else if(File.Exists(fileName)) {
      //file not exists
   } else {
     // read it 
     StreamReader sr = new StreamReader(fileName);
    //..
  }

Note: it is not right way to manipulate xml files. check out the XML documentation for more info.

Upvotes: 0

Jason Meckley
Jason Meckley

Reputation: 7591

the value of textbox1 is null or empty. also, if you want to manipulate xml look into the objects of the System.Xml namespace. These objects are designed specifically for working with XML.

Upvotes: 1

CloudyMarble
CloudyMarble

Reputation: 37566

You should make sure the file exists before you try to access it, it seems you deliver an empty string as a filename.

try accessing the file only when:

if (File.Exists(textBox1.Text))
{
  //Your Code...
}

Upvotes: 3

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

That is because your textBox1 doesn't contain text at the moment you create StreamReader. You set textBox1 text in button1_Click, so you have to create StreamReader in that method.

Upvotes: 8

Related Questions