我需要我的应用程序来查找和修改.swp文件(由VBA for SOLIDWORKS生成)中的文本字符串。如果我在Notepad++中以文本形式打开上述文件,大部分文本如下所示(这是一个摘录):

这意味着有可读的文本,以及显示为NUL、BEL、EXT等的符号,这取决于所选的编码。如果我通过Notepad++进行更改(查找"1.38“并将其更改为"1.39"),则没有问题,该文件可以通过SOLIDWORKS打开,并且仍然被识别为有效。毕竟,我不需要修改这些不可读的部分。但是,如果我在VB.NET应用程序中执行相同的修改,
Dim filePath As String = "D:\OneDrive\Desktop\launcher macro.swp"
Dim fileContents As String = My.Computer.FileSystem.ReadAllText(filePath, Encoding.UTF8).Replace("1.38", "1.39")
My.Computer.FileSystem.WriteAllText(filePath, fileContents, Encoding.UTF8)然后该文件被损坏,并且不再被SOLIDWORKS识别。我怀疑这是因为ReadAllText和WriteAllText无法处理这些不可读位中的任何数据。
我尝试了许多不同的编码,但似乎没有什么不同。我不确定Notepad++是如何做到这一点的,但我似乎不能在我的VB.NET应用程序中获得相同的结果。
有人能给点建议吗?
发布于 2021-03-08 18:54:28
感谢@jmcilhinney,这是一个对我有效的解决方案-将文件作为字节读取,转换为字符串,然后使用ANSI格式进行保存:
Dim file_name As String = "D:\OneDrive\Desktop\launcher macro.swp"
Dim fs As New FileStream(file_name, FileMode.Open)
Dim binary_reader As New BinaryReader(fs)
fs.Position = 0
Dim bytes() As Byte = binary_reader.ReadBytes(binary_reader.BaseStream.Length)
Dim fileContents As String = System.Text.Encoding.Default.GetString(bytes)
fileContents = fileContents.Replace("1.38", "1.39")
binary_reader.Close()
fs.Dispose()
System.IO.File.WriteAllText(file_name, fileContents, Encoding.Default)https://stackoverflow.com/questions/66525274
复制相似问题