我正在使用窗体应用程序窗口。我创建了一个文本文件。
Dim file As String = "C:\textfile.txt"
If System.IO.File.Exists(file) = True Then
If locid = txtvalue Then
Else
Dim objWriter As New System.IO.StreamWriter(file, True)
file = file.Replace(txtvalue, loc)
objWriter.WriteLine(file, loc)
objWriter.Close()
End If
End if
在这两个值中分别是thertxtvalue
和loc
valu ..如果该值不相同,那么我想txtvalue
用loc
value代替我。
txtvalue
是文本文件中的现有值,
loc
是
执行此代码后代码中的新值,我也同时获得了这两个值,而不是用新值替换现有值。新代码有什么问题
从您的问题来看,我认为您想要这样的东西(未经测试)
Dim NewValue = "Something to store"
Dim Path = "..."
If IO.File.Exists(Path)
'Read existing value
Dim Existing = IO.File.ReadAllText(Path)
If Existing <> NewValue
'It's different to the new value, overwrite it.
IO.File.WriteAllText(Path, NewValue)
End If
Else
'File doesn't exist. Create it
IO.File.WriteAllText(Path, NewValue)
End If
这样可以避免在内容未更改的情况下写入文件...当然,如果数据很小(小于兆字节),则您不是要避免与打开的文件句柄发生冲突,并且不要在文件中进行此操作。紧密循环,无论如何,最好还是编写一下……
IO.File.WriteAllText(Path, NewValue)
它更具可读性/可维护性,一次性写入的开销应该可以忽略不计。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句