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

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?

Related

vb check for specific file type in dir and perform code

I'm trying to make a program that checks for specific file type in a directory, then executes a code if there are any files of that type found.
I'm assuming something like this:
For Each foundFile As String In
My.Computer.FileSystem.GetFiles(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
(If any found files are, for example, "txt" files, then display their content.)
Next
Thanks in advance.
You can use Directory.GetFiles or Directory.EnumerateFiles with a parameter for the extension-filter:
Dim directoryPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim allTxtFiles = Directory.EnumerateFiles(directoryPath, ".txt")
For each file As String In allTxtFiles
Console.WriteLine(file)
Next
The difference between both methods is that the first returns a String(), so loads all into memory immediately whereas the second returns a "query". If you want to use LINQ it's better to use EnumerateFiles, f.e. if you want to take the first 10 files:
Dim firstTenFiles As List(Of String) = allTxtFiles.Take(10).ToList()
Dim di As DirectoryInfo = New DirectoryInfo(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
For Each fi In di.GetFiles("*.txt")
Dim content As String = My.Computer.FileSystem.ReadAllText(fi.FullName)
Console.WriteLine(fi.Name)
Next

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))

In vb.net, how do I get files from a directory based on a comma separated string?

I need to create an array() from files in a folder. Here's an example of how I would get all files within a folder.
Dim filesList = New DirectoryInfo("MyPath").GetFiles("*", SearchOption.TopDirectoryOnly).Where(Function(f) Not f.Attributes.HasFlag(FileAttributes.Hidden)).[Select](Function(f) New AClassNameHere(f)).ToArray()
I want to do the exact same thing, but only get files that exist in a comma separated string.
Dim myFiles as String = "filename1.jpg,filename2.jpg,filename3.jpg"
Where you see the AClassNameHere is a class I need to send each file to, and it would also be great if I knew how to send additional data about each file, like its type, size, etc.
Thank you kindly!
You could narrow the query results by adding an additional .Where() filter
Dim myFiles as String = "filename1.jpg,filename2.jpg,filename3.jpg"
Dim filesList = New DirectoryInfo("MyPath")
.GetFiles("*", SearchOption.TopDirectoryOnly)
.Where(Function(f) Not f.Attributes.HasFlag(FileAttributes.Hidden))
.Where(Function(f) myFiles.Contains(f.Name))
.[Select](Function(f) New AClassNameHere(f)).ToArray()
A better option would be to ensure that all filenames follow a pattern.
New DirectoryInfo("MyPath").GetFiles("filename*.jpg", SearchOption.TopDirectoryOnly)
Use this...
Dim Files() As String
Files= filesList.Split(",")
For each File In Files
Msgbox(File)
Next

dispose of IO.File.ReadAllLines

I am reading very large text files (6-10 MB). I am splitting the text files in to multiple new text files. There is common "header" and "footer" in the "read" text file that I will store as variable to be called at later time. I can't figure out how to properly dispose of IO.File.ReadAllLines. I'm concerned this will be held in memory if I don't dispose of it properly.
Text.Dispose or Text.Close isn't valid.
Dim testHeader As String
Dim testSite As String
Dim testStart As String
Dim testStop As String
Dim testTime As String
Dim text() As String = IO.File.ReadAllLines("C:\Users\anobis\Desktop\temp.txt")
testHeader = text(0)
testSite = text(text.Length - 4)
testStart = text(text.Length - 3)
testStop = text(text.Length - 2)
testTime = text(text.Length - 1)
text.dispose()
Later in the program I will be initiating another StreamReader and want to avoid conflicts and memory resource issues. I am new at coding so be gentle! Thanks!
' Open temp.txt with "Using" statement.
Using r As StreamReader = New StreamReader("C:\Users\anobis\Desktop\temp.txt")
' Store contents in this String.
Dim line As String
line = r.ReadLine
' Loop over each line in file, While list is Not Nothing.
Do While (Not line Is Nothing)
If line Like (sourceSN.Text + "*") Then 'Substitute in source serial number "xxxxxx*"
file.WriteLine(line)
End If
' Read in the next line of text file.
line = r.ReadLine
Loop
End Using
file.WriteLine(testSite)
file.WriteLine(testStart)
file.WriteLine(testStop)
file.WriteLine(testTime)
' Close transfer.txt file
file.Close()
You don't need to dispose of it. It returns a managed string array, who's lifetime is managed by the garbage collector. Internally, File.ReadAllLines is disposing of the underlying native file handle it created to read all of the lines for you.

How to replace CRLF with a space?

How can I parse out undesireable characters from a collection of data?
I am working with existing VB.NET code for a Windows Application that uses StreamWriter and Serializer to output an XML document of transaction data. Code below.
Private TransactionFile As ProjectSchema.TransactionFile
Dim Serializer As New Xml.Serialization.XmlSerializer(GetType (ProjectSchema.TransactionFile))
Dim Writer As TextWriter
Dim FilePath As String
Writer = New StreamWriter(FilePath)
Serializer.Serialize(Writer, TransactionFile)
Writer.Close()
The XML document is being uploaded to another application that does not accept "crlf".
The "TransactionFile" is a collection of data in a Class named ProjectSchema.TransactionFile. It contains various data types.
There are 5 functions to create nodes that contribute to the creation of a Master Transaction file named TransactionFile
I need to find CRLF characters in the collection of data and replace the CRLF characters with a space.
I am able to replace illegal characters at the field level with:
.Name = Regex.Replace((Mid(CustomerName.Name, 1, 30)), "[^A-Za-z0-9\-/]", " ")
But I need to scrub the entire collection of data.
If I try:
TransactionFile = Regex.Replace(TransactionFile, "[^A-Za-z0-9\-/]", " ")
Because TransactionFile cannot be converted to String I get a "Conversion from type 'Transaction' to type 'String' is not valid" message.
Bottom Line = How can I replace CRLF with a space when it shows up in TransactionFile data?
Don't do it this way. Create the serializer with XmlWriter.Create(). Which has an overload that accepts an XmlWriterSettings object. Which has lots of options to format the generated XML. Like NewLineChars, it lets you set the characters to use for a line end.
As Hans says, mess around with the XmlWriterSettings.
The next best choice is to write the file, then read the file into an xml object and process it element by element. This would let you remove crlf from within individual elements, but leave the ones between elements alone, for example.
Another possibility - rather than write directly to the file, you can make an intermediate string, and do a replace in that:
Dim ms As New MemoryStream
Serializer.Serialize(ms, TransactionFile)
ms.Flush()
ms.Position = 0
Dim sr As New StreamReader(ms)
Dim xmlString As String = sr.ReadToEnd
sr.Close() ' also closes underlying memorystream
Then you could do your regex replace on the xmlString before writing it to a file. This should get all the crlf pairs, both within elements and between.