2014-02-06 101 views
0

我創建VALIDCCC.TXT,我需要寫一些內容到這個文本文件,內容如下圖所示如何將內容寫入到文本文件在vb.net

內容:

00 A0 
00 A1 
00 A2 
10 A0 
10 A1 

我的代碼爲跟隨:

filepath = filepath + "\" + strsubmenu + "\" 

If (Not System.IO.Directory.Exists(filepath)) Then 
    System.IO.Directory.CreateDirectory(filepath) 
End If 

filepath = filepath + "MATRIX\" 
If (Not System.IO.Directory.Exists(filepath)) Then 
    System.IO.Directory.CreateDirectory(filepath) 
End If 

filepath = filepath + "VALIDCCC.TXT" 
If (Not System.IO.Directory.Exists(filepath)) Then 
    File.Create(filepath) 
End If 

File.WriteAllText(filepath, String.Empty) 
Dim objWriter As New System.IO.StreamWriter(filepath, True) 

For Each Customeritem As ListItem In CustomerCodeDVListBox.Items 

    For Each CCCitem As ListItem In CCCListBox.Items 
     objWriter.WriteLine(Customeritem.ToString() + Space(4) + CCCitem.ToString()) 
    Next 
Next 

我有2個列表框組合這個列表框的選擇值應該寫入文本文件。 如果VALIDCCC.TXT存在我需要清除的內容或用新內容覆蓋書寫內容之前...

+0

有幾十個與有關書面文本從vb.net文件,包括那些解釋追加對截斷答案的問題在這裏。例如,從[開始](http://stackoverflow.com/q/5002529/62576)開始。 「StreamWriter」的第二個參數決定完成哪項工作,文檔中明確說明了這一點。 –

+0

http://stackoverflow.com/questions/5002529/how-to-write-textbox-values-to-txt-file-with-vb-net當我實現相同的拋出錯誤:「進程無法訪問文件因爲它正在被另一個進程使用vb.net「 – Kapil

+0

這是因爲你用'File.Create'創建了同一個文件。閱讀你自己的代碼。您需要使用'File'或'StreamWriter',但不能同時在同一個文件上執行這兩個操作。 –

回答

0

這是工作......

filepath = filepath + "VALIDCCC.TXT" 
       Dim objWriter As StreamWriter 

       Dim sb As New StringBuilder 
       For Each Customeritem As ListItem In CustomerCodeDVListBox.Items 
        If Customeritem.Selected Then 
         For Each CCCitem As ListItem In CCCListBox.Items 
          If CCCitem.Selected Then 
           sb.Append(Customeritem.ToString() + Space(4) + CCCitem.ToString()) 
           sb.Append(Environment.NewLine) 
          End If 
         Next 
        End If 
       Next 

       If (Not System.IO.Directory.Exists(filepath)) Then 
        objWriter = File.CreateText(filepath) 
        objWriter.WriteLine(sb.ToString()) 
        objWriter.Close() 
       End If 
-1

看看這有助於:

filepath = filepath + "\" + strsubmenu + "\MATRIX\VALIDCCC.TXT" 
Dim DirPath As String = Path.GetDirectoryName(filepath) 
If Not Directory.Exists(dirpath) Then 
    Directory.CreateDirectory(dirpath) 
End If 
Dim objWriter As New System.IO.StreamWriter(filepath) 

For Each Customeritem As ListItem In CustomerCodeDVListBox.Items 

    For Each CCCitem As ListItem In CCCListBox.Items 
     objWriter.WriteLine(Customeritem.ToString() + Space(4) + CCCitem.ToString()) 
    Next 
Next 

這將創建任何文件夾是必要和覆蓋或創建根據需要輸入文本文件。

+0

對不起。不工作 – Kapil

+0

它怎麼樣不起作用? – tinstaafl