2013-10-14 18 views
0

我想從txt文件中讀取行到數組中並將其顯示到文本框中。 這裏是我的代碼:從text.file顯示列到數組c#

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (IsPostBack != true) 
    { 
     blogPostTextBox.Text =""; 
     string blogFilePath = Server.MapPath("~") + "/Blogs.txt"; 
     string[] blogMessageArray = File.ReadAllLines(blogFilePath); 

     // this for loop code does not work..I think.. 
     for (int i = 0; i < blogMessageArray.Length; i++) 
     { 
      string[] fileLineArray = blogMessageArray[i].Split(' '); 
      blogPostTextBox.Text = blogMessageArray[i] + System.Environment.New Line.ToString(); 
     } 
    } 
} 

我的文本文件包含幾行,我試圖分裂每一行陣列,通過一個for循環或while循環顯示所有行到一個文本框。

+0

那麼問題是什麼? – Rohit

+0

什麼是錯誤/輸出? –

回答

0

您需要將每行添加到文本框。上面的操作是用每一行新文本覆蓋文本框的內容。

string[] blogMessageArray = File.ReadAllLines(""); 
blogPostTextBox.Text = ""; 
foreach (string message in blogMessageArray) 
{ 
    blogPostTextBox.Text += message + Environment.NewLine; 
} 

雖然不是在所有行讀,然後寫了所有的線,你爲什麼不只是寫出來的所有文字文本框?

blogPostTextBox.Text = File.ReadAllText(); 
+0

你是對的..我正在覆蓋行..謝謝:) – user2699500

0

雖然你可以這樣做在一個循環,你真的不需要(或希望)

與建點網的方法,其實做什麼你需要更換你的循環。

See String.Join() 

public static string Join(
    string separator, 
    params string[] value 
) 

這將(在你的情況下,「\ n」,HTML並不需要爲「\ r \ n」),將所有blogMessageArray的元素與你指定的分隔

然後就分配這物業blogPostTextBox.Tex

1

你必須設置TextMode="MultiLine"TextBox(默認值是SingleLine),那麼你可以建立使用LINQ中的文本是這樣的:

var allLinesText = blogMessageArray 
    .SelectMany(line => line.Split().Select(word => word.Trim())) 
    .Where(word => !string.IsNullOrEmpty(word)); 
blogPostTextBox.Text = string.Join(Environment.NewLine, allLinesText); 
+0

1+爲什麼有兩次加入'環境。NewLine',它會產生空行 – Damith

+0

@Damith:謝謝,你說得對。相應地編輯我的答案。 –

3

UPDATE:

對於ASP.Net

var items =File.ReadAllLines(blogFilePath).SelectMany(line => line.Split()).Where(x=>!string.IsNullOrEmpty(x)); 
blogPostTextBox.Text=string.Join(Environment.NewLine, items) 

,並作爲一個側面說明,它是更好地使用Path.Combine當您從多個字符串構建路徑

string blogFilePath = Path.Combine(Server.MapPath("~") , "Blogs.txt"); 

也有if (IsPostBack != true)是有效的,但你可以做爲

if (!IsPostBack) 

WinForm的

如果文本框控件的多行屬性設置爲true,則可以使用TextBoxBase.Lines Property

blogPostTextBox.Lines =File.ReadAllLines(blogFilePath); 

,如果你需要分割每一行,並設置as textbox text then

blogPostTextBox.Lines = File.ReadAllLines(blogFilePath).SelectMany(line => line.Split()).ToArray(); 
+1

不錯,不知道有一個Lines屬性 –

+0

我認爲這是ASP.NET,因爲OP使用了'IsPostBack'屬性和'Server.MapPath',在[ASP.NET-'TextBox'上沒有'Lines'屬性](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox_properties.aspx)。 –

+0

@TimSchmelter是的,你是對的。謝謝 – Damith