c# - 串流阅读器问题

标签 c# .net

我是一个真正的 C# 菜鸟,试图根据我的一个 friend 在他的一个应用程序中使用的短代码编写一个小型 XML 替换程序。

我在使用这条线时遇到了问题:

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

    }


}
}

提前致谢:)

最佳答案

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

关于c# - 串流阅读器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8656783/

相关文章:

c# - 如何将图表更改为列渐变填充样式?

c# - 如何覆盖 ToString() 方法以输出列表?

c# - 通过 LINQ to SQL 中的新对象更新实体

c# - Linq lambda 连接错误

c# - 提供 SqlDbType 的有效方式?

c# - 如何从列表中提取双引号内的所有内容?

c# - 什么是 System.Reactive.Linq.Observαble? (注意阿尔法)

c# - '检测到没有 [Pure] 的方法调用'......但是 Pure 在那里

.net - 我可以使用 XDocument.Save 并排除 XML 声明吗?

c# - Windows Mobile 开发 : Choice of .Net compact vs. Native (c++) 代码