VB.NET: Modifying non-text file as text without ruining it - vb.net

I need my application to find and modify a text string in a .swp file (generated by VBA for SOLIDWORKS). If I open said file as text in Notepad++, most of the text looks like this (this is an excerpt):
Meaning there is readable text, and symbols that appear as NUL, BEL, EXT and so on, depending on selected encoding. If I make my changes via Notepad++ (finding and changing "1.38" to "1.39"), there are no issues, the file can be opened via SOLIDWORKS and is still recognized as valid. After all, I don't need to modify these non-readable bits. However, if I do the same modification in my VB.NET application,
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)
then the file gets corrupted, and is no longer recognized by SOLIDWORKS. I suspect this is because ReadAllText and WriteAllText cannot handle whatever data is in these non-readable bits.
I tried many different encodings, but it seems to make no difference. I am not sure how Notepad++ does it, but I can't seem to get the same result in my VB.NET application.
Can someone advise?

Thanks to #jmcilhinney, this is a solution that worked for me - reading file as bytes, converting to string, and then saving, using ANSI formatting:
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)

Related

How to recombine document pages stored as separate Base64 strings in FileNet using VB.Net?

I have a document that is stored on FileNet. Each page of the document is stored as a separate base 64 encoded string. I need to get all of these pages into a single document again.
What I have attempted to do is to decode the Base64 string into an array. for each page of the document, I decode the Base64 string into a byte array using concatenation. I then use the File.WriteAllBytes method to create a single file. This file is a valid TIFF file and I am able to open it however only the last page appears. I have checked to make sure that the application I am using to open the document is capable of showing more than one page. I am using the Windows Photos application which will show all pages of a TIFF document.
How can I merge the pages of this document so that each page will appear correctly?
For example, the code below reads the Base64 string for each file and then combines them into a single output file. When I open bytefileout3.tiff however, I can only see the last page that was added into the document.
Dim inputPath As String = "C:\temp\file1.txt"
Dim fileStr As String = File.ReadAllText(inputPath)
Dim bytes As Byte() = Convert.FromBase64String(fileStr)
Dim inputPath2 As String = "C:\temp\file2.txt"
Dim fileStr2 As String = File.ReadAllText(inputPath2)
Dim bytes2 As Byte() = Convert.FromBase64String(fileStr2)
Dim bytes3 As Byte() = New Byte() {}
File.WriteAllBytes("c:\temp\bytefileout.tiff", bytes)
File.WriteAllBytes("c:\temp\bytefileout2.tiff", bytes2)
bytes3 = bytes2.Concat(bytes).ToArray()
File.WriteAllBytes("c:\temp\bytefileout3.tiff", bytes3)

Reading a .dat file

I have a file I am trying to read and disply results into a text box. The file has no extension, but it is a 'data' file per the website (www.checkfiletype.com).
Here is a screen shot of how the file looks in a online reader, it looks like hex?
I have tried a stream reader, and gives nothing in results. Last method I tried was a BinaryReader, that I have never used before. The results from this is a "0" into the text box. Given that I have never used the BinaryReader function, I am sure I did something wrong with it.
Using reader As New BinaryReader(File.Open("C:\Users\jefhill\Desktop\CMOSDATA", FileMode.Open))
Dim pos As Integer = 0
Dim length As Integer = reader.BaseStream.Length
While pos < length
' Read the integer.
Dim value As Integer = reader.ReadInt32()
' Write to screen.
TextBox1.Text = value
' Add length of integer in bytes to position.
pos += 4
End While
End Using
Any help would be greatly appreciated.
EDIT
I tried using a basic StreamReader. With this, nothing happens, as in no errors, just puts nothing(blank) into the textbox.
Dim file As String = "C:\Users\jefhill\Desktop\CMOSDATA"
Dim reader As New System.IO.StreamReader(file)
TextBox1.Text = reader.ReadToEnd
reader.Close()
The file is not a text file, and cannot be directly displayed in a TextBox. You will need to find the format of the file and convert it to text in order to display it in a TextBox.

vb.net How to save File as Word & Open Office Document?

I have a small programm and i want to save the File so i can read them later into when i open it.
How can i now save the File cause i must save 5 Variables and read them back into the Tool and if its possible i want to use the File in Word or OpenOffice too.
My Variables
Title - Pieces- SinglePrice- Totalprice
Please give me Examples for the Point in the right way.
Thanks everyone!
If all you want to do is store four variables from your program in a file that can also be read by Word and OpenOffice, you can do that easily enough with a text file. The following code assumes that Title is a String, Pieces is an Integer, SinglePrice and TotalPrice are Decimal.
Dim folder As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim saveFile As String = System.IO.Path.Combine(folder, "Save.txt")
Dim vars() As String = {Title, Pieces.ToString, SinglePrice.ToString, TotalPrice.ToString}
System.IO.File.WriteAllLines(saveFile, vars)
If you need to read the file to restore the values of the variables, you can do it like this. Note that this code assumes that the file was written by the first snippet of code, otherwise it would be necessary to validate the contaents of the file before using it.
Dim folder As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim saveFile As String = System.IO.Path.Combine(folder, "Save.txt")
Dim vars() As String = System.IO.File.ReadAllLines(saveFile)
Title = vars(0)
Pieces = CInt(vars(1))
SinglePrice = CDec(vars(2))
TotalPrice = CDec(vars(3))

Can I stop my textbox from crashing when loading in too much data into it?

Not sure if this is something really simple that I haven't noticed. Or just a simple try/catch (I guess most likely).
I have a textbox on a form. It takes in data from another text file which is very large (lets assume 1Mb) and in a lot of cases it can take it but in some cases the program crashes when loading the file.
How can I handle this?
You could try to read the file size of the text file before loading it into your text box. If the length of the file is greater than the capacity of your text box, you can prevent the text box from being filled.
You can use a function like File.ReadAllLines to determine the size of the text file.
Dim AppDataLocation As String = "C:\Files\TestFiles\"
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(AppDataLocation)
For Each fileSystemInfo As System.IO.FileSystemInfo In _
SourceDirectoryInfo.GetFileSystemInfos
Dim FileText As String = System.IO.File.ReadAllText _
(AppDataLocation & fileSystemInfo.Name)
Next
Alternately, you can use FileInfo.Length as seen in this example here.
Dim file As New FileInfo("file.txt")
Dim sizeInBytes As Long = file.Length

trying to read a delimited text file from resources - but it wont run

I'm having a problem where instead of reading a text file from the location string, I changed it to read the text file from the resource location and it breaks my program. I've also used the insert snippet method to get most of this code, so it is safe to say I don't know what is going on. Could some one please help?
'reads the text out of a delimited text file and puts the words and hints into to separate arrays
' this works and made the program run
' Dim filename As String = Application.StartupPath + "\ProggramingList.txt"
'this dosnt work and brings back a Illegal characters in path error.
dim filename as string = My.Resources.ProggramingList
Dim fields As String()
'my text files are delimited
Dim delimiter As String = ","
Using parser As New TextFieldParser(filename)
parser.SetDelimiters(delimiter)
While Not parser.EndOfData
' Read in the fields for the current line
fields = parser.ReadFields()
' Add code here to use data in fields variable.
'put the result into two arrays (the fields are the arrays im talking about). one holds the words, and one holds the corresponding hint
Programingwords(counter) = Strings.UCase(fields(0))
counter += 1
'this is where the hint is at
Programingwords(counter) = (fields(1))
counter += 1
End While
End Using
the error
ex.ToString()
"System.ArgumentException: Illegal characters in path.
at System.IO.Path.CheckInvalidPathChars(String path)
at System.IO.Path.NormalizePathFast(String path, Boolean fullCheck)
at System.IO.Path.NormalizePath(String path, Boolean fullCheck)
at System.IO.Path.GetFullPathInternal(String path)
at System.IO.Path.GetFullPath(String path)
at Microsoft.VisualBasic.FileIO.FileSystem.NormalizePath(String Path)
at Microsoft.VisualBasic.FileIO.TextFieldParser.ValidatePath(String path)
at Microsoft.VisualBasic.FileIO.TextFieldParser.InitializeFromPath(String path, Encoding defaultEncoding, Boolean detectEncoding)
at Microsoft.VisualBasic.FileIO.TextFieldParser..ctor(String path)
at HangMan.Form1.GetWords() in I:\vb\HangMan\HangMan\Form1.vb:line 274" String
The TextFieldParser constructor you use expects the name of a file. Instead, it gets the contents of the file. That goes Kaboom, the file content is not a valid path to a file. You'll need to the constructor that takes a Stream and use the StringReader class to provide the stream. For example:
Dim fields As String()
Dim delimiter As String = ","
Dim fileContent As String = My.Resources.ProggramingList
Dim stringStream as New System.IO.StringReader(fileContent)
Using parser As New TextFieldParser(stringStream)
REM etc...
End Using
This is a bit wasteful of memory but not an issue if the text is less than a megabyte or so. If it is more then you shouldn't put it in a resource.
When you debug this code, what is the value of the variable filename after you read it from My.Resources.GamesList? Is it a valid string, does it point to you're file?