2011-12-28 83 views
2

我是一个真正的小白到C#试图写基于短代码在自己的应用程序中的一个使用我的一个朋友小XML替代品方案..StreamReader的问题

我在这条线的麻烦:

StreamReader sr = new StreamReader(textBox1.Text); 

我收到一个错误:“空路径名称不合法。” 为什么不工作?

代码:

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; 
     } 

    } 


} 
} 

感谢提前:)

+0

一个不相关的说明:你应该把你的流包装在using子句中。这将确保即使发生异常也会调用Close()。 – 2011-12-28 14:09:17

+1

也注意:避免在构造函数中做这样的功能 - 你最终在设计器中出错 – Reniuz 2011-12-28 14:13:04

回答

3

在尝试访问文件之前,应该确保该文件已存在,看起来您会将空字符串作为文件名提供。

尝试访问该文件,只有当:

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

工程很好,谢谢! – Zbone 2011-12-30 09:33:47

8

那是因为你textBox1不包含在创建StreamReader的那一刻文本。您在button1_Click中设置了textBox1文本,因此您必须在该方法中创建StreamReader

1

TextBox1中的值为null或空。另外,如果你想操作xml,查看System.Xml命名空间的对象。这些对象专门用于处理XML。

0

这是因为您在StreamReader构造函数中设置了空字符串。

我建议你在读取文件之前做一个简单的验证。

就象这样:

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); 
    //.. 
    } 

注:这不是处理XML文件的正确途径。 查看XML documentation了解更多信息。

+0

为什么downvoted? ? – Kakashi 2011-12-28 14:52:36