2011-12-28 35 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