2013-10-26 16 views
0

我想從文本框中的文本文件中的指定值寫入數據。這裏是一個例子:以特定的值和行寫入文件

item_begin etcitem 3344 item_type=etcitem是第一行,而item_begin weapon 3343 item_type=weapon是第二位。那麼我想在item_type=armor的第二行代替item_type=weapon。以下是目前爲止的代碼:

var data2 = File.WriteAllLines("itemdata.txt") 
    .Where(x => x.Contains("3343")) 
    .Take(1) 
    .SelectMany(x => x.Split('\t')) 
    .Select(x => x.Split('=')) 
    .Where(x => x.Length > 1) 
    .ToDictionary(x => x[0].Trim(), x => x[1]); 

但是在WriteAllLines處返回錯誤。 下面是readline的部分代碼:

var data = File.ReadLines("itemdata.txt") 
    .Where(x => x.Contains("3343")) 
    .Take(1) 
    .SelectMany(x => x.Split('\t')) 
    .Select(x => x.Split('=')) 
    .Where(x => x.Length > 1) 
    .ToDictionary(x => x[0].Trim(), x => x[1]); 
//call values 

textitem_type.Text = data["item_type"]; 

而且想寫我改變textitem_type.Text讀取後的值相同。

我用它來重新生成,但用行中的同名替換所有的值,並在文本中只返回1行。代碼:

private void button2_Click(object sender, EventArgs e) 
    { 
     var data = File 
        .ReadLines("itemdata.txt") 
        .Where(x => x.Contains(itemSrchtxt.Text)) 
        .Take(1) 
        .SelectMany(x => x.Split('\t')) 
        .Select(x => x.Split('=')) 
        .Where(x => x.Length > 1) 
        .ToDictionary(x => x[0].Trim(), x => x[1]); 
     StreamReader reader = new StreamReader(Directory.GetCurrentDirectory() + @"\itemdata.txt"); 
     string content = reader.ReadLine(); 
     reader.Close(); 
     content = Regex.Replace(content, data["item_type"], textitem_type.Text); 
      StreamWriter write = new StreamWriter(Directory.GetCurrentDirectory() + @"\itemdata.txt"); 
     write.WriteLine(content); 
     write.Close(); 
    } 
+0

沒有人可以幫忙嗎? – user2828891

+0

我幫了忙,請upvote:P – Krekkon

回答

0

請嘗試更換WriteAllLinesReadAllLines

var data2 = File.ReadAllLines("itemdata.txt"); 

//use linq if you want, it just an example fo understandin 
Foreach (var dataline in data2) 
{ 
    if (dataline.Contains("3343")) 
     dataline = "item_begin weapon 3343 item_type=weapon" //of course you can use the split, it just an example 
} 

File.WriteAllLines("itemdata.txt", data2); 
+0

我更新了我的第一篇文章,以便更清楚。 – user2828891

+0

我也更新了,也許它可以幫助簡單的讀寫邏輯。請訪問http://msdn.microsoft.com/en-us/library/dd383693.aspx頁面以瞭解WriteAll方法 – Krekkon

+1

更改循環中數據線的值不會更改數組的內容。 –

相關問題