I want to write some text to a .txt file, this is what I have, and it works mostly:
If System.IO.File.Exists(sListItems) = True Then
Dim writeToFile As New System.IO.StreamWriter(sListItems, True)
writeToFile.WriteLine(vbCrLf & txtGameTitle.Text)
writeToFile.Close()
Else
MsgBox("Error!")
End If
End If
The problem is with that, when I enter text such as 'Hello', it would instead put into the txt file 'Hello ' (with a space). Is there anyway to resolve this?
Don't use File.Exists(). It's a race condition waiting to blow up, and it's slower. Instead, look for the FileMode that matches how you want to use the file; then handle the exception if it fails (you need to handle the exception anyway, because of the race condition potential mentioned earlier).
Additionally, if you have your Using blocks correct, you don't need to call .Close().
Try
Using fs As New FileStream(sListItems, FileMode.Open)
fs.Seek(0, SeekOrigin.End)
Using sw As New StreamWriter(fs)
sw.WriteLine(txtGameTitle.Text)
End Using
End Using
Catch ex As IOException
MsgBox("Error! -- " & ex.Message)
End If
But I wonder if you really care that the file already exists, and all you really need to do is this:
File.AppendAllText(sListItems, txtGameTitle.Text)
Well, I think I figured it out. I changed:
writeToFile.WriteLine()
to
writeToFile.Write()
and it no longer gives spaces.
Edit:
I know what my problem was, I was using lbGameList.SelectedItem.ToString() to find the name and it was giving me spaces, so I added .TrimEnd to it and it works now, thanks
Related
I want to create a fake run box to use against Technical Support Scammers to waste their time. I want to have some specified text run a msgbox. Is there a way to accept all cases? (notepad, NoTePaD, NOTEPAD etc.).
If textbox1.text = "Notepad" Then
Msgbox("Unable to open")
I'm a bit confused as to what "all versions of it" means, however the following will ignore spaces and capitalization:
Dim str As String = textbox1.text.ToLower().Replace(" ", "")
If str = "notepad" Then MsgBox("Unable to open")
This is a VB.Net solution, however as Plutonix mentioned in the comments, it's hard to tell what sort of solution you're looking for - you've tagged two different types of VB.
I was given a file that was created with a java program but does not have LF or endofline ending so I am working with a gigantic string. I tried splitting and then using the TextFieldParser but it seems the file is just too big to deal with. The contents are vital to I need to get this data somehow and then clean it up. Here is what I have tried:
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\Users\Desktop\META3.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
End Using
I think the best way is to take substrings of the text and I wanted to take all values after the 7 occurrences of a comma which is what the file should have per line. Not sure how to do this and it seems like regex maybe the only option. Any ideas appreciated.
line = freader.Readline()
Dim ms As Match = Regex.Match(line, "(\w+),(\w+),(\w+),(\w+),(\w+),(\w+),")
line = ms.Value
will this work; does not give expected results.
If you can be guaranteed that the number of columns is always consistent why not add a counter that reads each column and then goes onto the next set. You can then create a new spreadsheet or file with the correct format. If you do an search on here there is a package for .net which allows you to build valid .xls and .xlsx files on the fly. The package is called "simple ooxml". i have used this to create all sorts of spreadsheets where I work. I built a command line app that passes and xml file with parameters and builds this as a fully fledged spreadsheet. Hope the above helps. Any questions let me know.
I'm writing a windows service which runs as the local system account. I'm trying to make sure if I have full read/write access to a file beginning to process it any further. Here is my code:
Dim FullPath As String
FullPath = "C:\directory\file.txt"
Dim ps As Security.PermissionSet
ps = New Security.PermissionSet(Security.Permissions.PermissionState.Unrestricted)
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, FullPath))
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, IO.Path.GetDirectoryName(FullPath)))
Try
ps.Demand()
Catch ex As Security.SecurityException
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
Catch ex As Exception
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
End Try
Then I set the full access permissions for the file to "Deny" for the user account my service is running as. After executing, the code above doesn't throw any exceptions and allows file processing to begin. When the service later tries to change and/or delete the file, I get an "Access Denied" exception.
Any suggestions?
For this purpose i use thise small function:
Private Function HasAccess(ByVal ltFullPath As String)
Try
Using inputstreamreader As New StreamReader(ltFullPath)
inputstreamreader.Close()
End Using
Using inputStream As FileStream = File.Open(ltFullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
inputStream.Close()
Return True
End Using
Catch ex As Exception
Return False
End Try
End Function
In your case then:
If HasAccess(FullPath) ...
I have solved the problem by using My.Computer.FileSystem.DeleteFile to delete the file instead of Kill. My.Computer.FileSystem.DeleteFile was executed without problems after successfully demanding full read/write access to the file in the way described above, while Kill consistently threw an "Access denied" exception.
Using "Kill"... I know this is a very old thread but I'll add this in case anyone stumbles on it like I did. I was working on some old VB6 legacy code. One of my clients users was getting a runtime exception during a file open after a kill. The code was "Killing" the file and then rebuilding it from scratch with binary data held in memory. It tuns out that the "Kill" function triggered the user's anti-virus software which locked the file long enough to cause the next "Open" statement to fail. I discovered this using an error logging utility (the name escapes me at the moment). The line in the error log file on the failed "Open" statement was that the file's status was "Delete pending" due to the user's anti-virus software.
I need to unzip en zip some files in my application using Shell32. Right now, I use srcFolder.CopyHere(destFolder.Items()) to achieve this. However, my next line of code requires the newly made ZIP-file. But since the CopyHere method is Async, how can I check when it in finished? Right now I use a Thread.Sleep for around 500 ms which is enough for my computer to finish creating the ZIP file, but it's not good code imo.
Any ideas?
More info/code can be provided if necessary.
Here is another one for waiting to finish copying
'Wait until the File/Folder has finished writing to zip file...
Do Until Shell.NameSpace(Filename).Items.Count = Shell.NameSpace(Input).Items.Count
System.Threading.Thread.Sleep(200)
System.Diagnostics.Debug.Print("Waiting...")
Loop
I found it, used something like this:
srcFolder.CopyHere(destFolder.Items())
While FileInUse(FILEPATH & "BudgetJaarOverzichtSMB.zip")
Thread.Sleep(100)
End While
Private Function FileInUse(ByVal FilePath As String) As Boolean
Try
FileOpen(1, FilePath, OpenMode.Input)
FileClose(1)
Return False ' File not in use
Catch ex As Exception
Return True ' File in use
End Try
End Function
Not really perfect but will lose less time than with my first approach.
I'm trying to import a tab delimited file into a table.
The issue is, SOMETIMES, the file will include an awkward record that has two "null values" and causes my program to throw a "unexpected end of file".
For example, each record will have 20 fields. But the last record will have only two fields (two null values), and hence, unexpected EOF.
Currently I'm using a StreamReader.
I've tried counting the lines and telling bcp to stop reading before the "phantom nulls", but StreamReader gets an incorrect count of lines due to the "phantom nulls".
I've tried the following code to get rid of all bogus code (code borrowed off the net). But it just replaces the fields with empty spaces (I'd like the result of no line left behind).
Public Sub RemoveBlankRowsFromCVSFile2(ByVal filepath As String)
If filepath = DBNull.Value.ToString() Or filepath.Length = 0 Then Throw New ArgumentNullException("filepath")
If (File.Exists(filepath) = False) Then Throw New FileNotFoundException("Could not find CSV file.", filepath)
Dim tempFile As String = Path.GetTempFileName()
Using reader As New StreamReader(filepath)
Using writer As New StreamWriter(tempFile)
Dim line As String = Nothing
line = reader.ReadLine()
While Not line Is Nothing
If Not line.Equals(" ") Then writer.WriteLine(line)
line = reader.ReadLine()
End While
End Using
End Using
File.Delete(filepath)
File.Move(tempFile, filepath)
End Sub
I've tried using SSIS, but it encounters the EOF unexpected error.
What am I doing wrong?
If you read the entire file into a string variable (using reader.ReadToEnd()) do you get the whole thing? or are you just getting the data up to those phantom nulls?
Have you tried using the Reader.ReadBlock() function to try and read past the file length?
At our company we do hundreds of imports every week. If a file is not sent in the correct, agreed to format for our automated process, we return it to the sender. If the last line is wrong, the file should not be processed because it might be missing information or in some other way corrupt.
One way to avoid the error is to use ReadAllLines, then process the array of file lines instead of progressing through the file. This is also a lot more efficient than streamreader.
Dim fileLines() As String
fileLines = File.ReadAllLines("c:\tmp.csv")
...
for each line in filelines
If trim(line) <> "" Then writer.WriteLine(line)
next line
You can also use save the output lines in the same or a different string array and use File.WriteAllLines to write the file all at once.
You could try the built-in .Net object for reading tab-delimited files. It is Microsoft.VisualBasic.FileIO.TextFileParser.
This was solved using a bit array, checking one bit at a time for the suspect bit.