2013-05-07 60 views
2

一直以來都是作爲新手(更多新手)關注線程,但現在開始做更多。VB.NET中的搜索/替換

我可以閱讀如何打開一個文本文件,但無法理解.replace功能(我得到的語法只是無法讓它工作)。

場景:

Inputfile name = test_in.txt 

替換{} inputfilec:\temp\test1.txt

我使用test.txt作爲一個腳本工具的模板,需要內一個新的文件名爲test_2.txt替換不同的值。

我已經有定義輸入和輸出文件沒有問題的變量,我只是無法捕捉打開新文件和替換的語法。

回答

2

你真的沒有給我們這麼多繼續。但是使用String.Replace的一個常見錯誤是,它會創建一個需要保存到另一個變量的源的副本,否則它將進入位桶。所以在你的情況下,像這樣的東西應該工作。

Dim Buffer As String 'buffer 
Dim inputFile As String = "C:\temp\test.txt" 'template file 
Dim outputFile As String = "C:\temp\test_2.txt" 'output file 

Using tr As TextReader = File.OpenText(inputFile) 
    Buffer = tr.ReadToEnd 
End Using 
Buffer = Buffer.Replace("templateString", "Hello World") 

File.WriteAllText(outputFile, Buffer) 
+0

一些偉大的想法夥計 - 謝謝你! 今晚我會在機場遇難的時候嘗試這個。將在一夜之間回覆你。 – 2013-05-07 16:55:10

+0

這工作真棒!我也能夠毫無問題地使用多個buffer.replace。 我很感激幫助,我希望我能在一天內回報它.. – 2013-05-07 19:22:43

+2

+1他用你的解決方案,你值得你的幫助。 – SysDragon 2013-05-09 15:50:38

1

嘗試是這樣的:

Dim sValuesToReplace() As String = New String() {"Value1", "Value2", "Value3"} 
Dim sText As String = IO.File.ReadAllText(inputFilePath) 

For Each elem As String In sValuesToReplace 
    sText = sText.Replace(elem, sNewValue) 
Next 

IO.File.WriteAllText(sOutputFilePath, sText) 

這取決於如果你想只有一個值來替換所有的值,或對每個不同的值。如果你需要不同的值,你可以使用一個Dictionary

Dim sValuesToReplace As New Dictionary(Of String, String)() 

sValuesToReplace.Add("oldValue1", "newValue1") 
sValuesToReplace.Add("oldValue2", "newValue2") 
'etc 

然後循環throgh它:

For Each oldElem As String In sValuesToReplace.Keys 
    sText = sText.Replace(oldElem, sValuesToReplace(oldElem)) 
Next