我是一个真正的 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/