I have the following method to save Custom As List of (CustomItem)" to a binary file:
Dim st As FileStream
Try
If Not Directory.Exists(Path.GetDirectoryName(FilePath)) Then Directory.CreateDirectory(Path.GetDirectoryName(FilePath))
st = File.Open(FilePath, FileMode.OpenOrCreate)
Dim SerialObj As New BinaryFormatter()
SerialObj.Serialize(st, Custom)
st.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
This doing great and I can read the content but after changing a string property in the "CustomItem" class and saving the file again it saves the file without any issues. But the issue appears when I read the file again it gets that the file has zero "CustomItem"(s) but it has at least 3 "CustomItem"s inside the file.
Sorry for lengthiness,
but what can be the issue?
Related
I'm using .NET 4 on Windows 10.
I have a winform application written in vb.net which converts TIFF into PDF using PDFSharp api.
When I try to save the PDF into the C:\ folder there is no exception raised but nothing is written.
When I check if I have write access permission on folder C:\ , VB.NET tells me I do.
I'm using this chunk of code:
Private Function HasFolderWriteAccess(path As String) As Boolean
Try
Using inputstreamreader As New StreamReader(path)
inputstreamreader.Close()
End Using
Using inputStream As FileStream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None)
inputStream.Close()
Return True
End Using
Catch ex As Exception
Return False
End Try
End Function
When I try to write a file using a StreamWriter, I face the same behavior:
Dim FILE_NAME As String = "C:\test2.txt"
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
objWriter.Write("Some text....")
objWriter.Close()
MessageBox.Show("Text written to file")
Is there some kind of magic happening in the Windows 10 C:\ folder that I don't know ?
Thanks for your replies.
Chris Dunaway's answer (in the comments) is right:
...look in this folder instead: C:\Users\User_name\AppData\Local\VirtualStore and see if your file is there. Windows doesn't allow writing of files to certain folders and silently redirects them to the virtual store...
Please take a look at this code. For some reason that I can't figure out, the File.Delete() line isn't getting fired and I'm not getting an error.
' hard-coded for testing
Dim path As String = "C:\Program Files (x86)\Test\Program\Program.exe"
Dim appDir As String = My.Application.Info.DirectoryPath
Dim iniPath As String = appDir & "\config.ini"
Dim outputPath As String = appDir & "\output.ini"
Dim textLine As String = ""
Dim reader = File.OpenText(iniPath)
Dim writer = New StreamWriter(outputPath)
' Read the lines in the ini file until the pathToExecutable line is found and write the path to that line
While (InlineAssignHelper(textLine, reader.ReadLine())) IsNot Nothing
If textLine.StartsWith("pathToExecutable=") Then
writer.WriteLine("pathToExecutable=" & path)
Else
writer.WriteLine(textLine)
End If
End While
reader.Dispose()
reader.Close()
writer.Dispose()
writer.Close()
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Return path
You stated that you are not getting an error, but if you don't implement exception handling, you're most probably getting errors and throwing them away (pun intended).
Use a try/catch around any of your System.IO.File operations, and even more, you can implement specific handles and catch specific exceptions.
Try
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Catch ioException As IOException
'The specified file is in use.
MessageBox.Show(ioException.Message)
Catch ex As Exception
'Some other error apart for file in use.
MessageBox.Show(ex.Message)
End Try
Ericosg's suggestion about using a try/catch lead me to the issue: I had the file open in a streamreader earlier in my code, but never closed it there.
I need download a CSV file and then read it. Here is my code:
tickerValue = "goog"
Dim strURL As String = "http://ichart.yahoo.com/table.csv?s=" & tickerValue
Dim strBuffer As String = RequestWebData(strURL)
Using streamReader = New StreamReader(strBuffer)
Using reader = New CsvReader(streamReader)
I keep getting this error: An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll Additional information: Illegal characters in path.
What am I doing wrong?
Additional Info
In another part of my program I use this code and it works fine.
Address = http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=AMEX&render=download
Dim strBuffer As String = Historical_Stock_Prices.RequestWebData(Address)
Using streamReader = New StringReader(strBuffer)
Using reader = New CsvReader(streamReader)
Isn't my second code the same concept as my problem code?
you are giving it, essentially, a web url. somewhere in your code, it does not support the web url. it could be the streamreader. it could be the CsvReader.
what line of code does this point to?
the best bet is to save the file TO DISK, then read from disk.
UPDATE
here is an example to SAVE to disk:
using writer as new StreamWriter("C:\Test.csv")
writer.Write(strBuffer)
writer.Close()
end using
here is an example to READ from disk:
using strReader as new StreamReader("C:\Test.csv")
' this code is presumably how it works for reading into the CsvReader:
using reader as new CsvReader(strReader)
' now do your thing
end using
strReader.Close()
end using
I have an SSIS package (SQL Server 2005) that loops through a bunch of flat files in a folder. I need to wait until the source application has finished writing the file before I can open it in my flat file import task.
I have a For Each loop container and within it a script task to execute before the Data Flow Task.
When I try to create the success connector between the Script Task and the Data Flow Task I get this error:
Could not create connector. Object reference not set to an instance of
an object.
I get that something is being set to nothing, but I can't see it. I have DelayValidation set to true on both the Script Task and the Data Flow Task. What else am I missing?
I'm a C# guy so maybe I'm missing something obvious in the VB. Here's the script I poached from the interwebs:
Public Sub Main()
Dim strFileName As String = CType(Dts.Variables("FileName").Value, String)
Dim objFS As System.IO.FileStream
Dim bolFinished As Boolean = False
Do
Try
objFS = System.IO.File.Open(strFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
bolFinished = True
objFS.Close()
Catch ex As Exception
System.Threading.Thread.Sleep(1000)
End Try
Loop
If bolFinished Then
Dts.TaskResult = Dts.Results.Success
Else
Dts.TaskResult = Dts.Results.Failure
End If
End Sub
Milen k is more than right. It looks like you have an infinite loop which is opening a file several times until it breaks down.
You could change your code with the below suggested code. This will help you to get out of the infinite loop.
Your current code:
Do
Try
objFS = System.IO.File.Open(strFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
bolFinished = True
objFS.Close()
Catch ex As Exception
System.Threading.Thread.Sleep(1000)
End Try
Loop
Suggested code:
Do While(true)
Try
objFS = System.IO.File.Open(strFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
bolFinished = True
objFS.Close()
Exit Do
Catch ex As Exception
System.Threading.Thread.Sleep(1000)
End Try
Loop
Make sure that you have created a Flat File Source for your Data Flow task. If you do not have an existing one, create a temporary one which act as a place-holder for the file paths you feed it through the For Each loop.
From what I understand, you should be passing the path to each file that you will be importing to your Flat File Connection. This can easily be done by adding the variable generated in your For Each loop as an expression in the Expression property of your Flat File Connection.
UPDATE:
You need to set a condition in your Do ... Loop. For example: Loop While Not bolFinished. Look at this document for more information.
I need to update the students score with a new score but I cant get it to write to the line that the students current score it at. It just deletes the whole text.
Alex,letmein,0
David,qwerty1,0
John,password,0
Paul,lion,0
Luke,bennett,0
Ronald,Mcdonald,0
Erin,german,0
Laura,Scotland,0
Ross,extra,0
Alan,beverage,0
Try
fileName = "C:\Documents and Settings\Student\Desktop\Task10\primary4.txt"
Dim sWriter As New System.IO.StreamWriter(fileName)
index = lblPosition.Text
sWriter.Write(username(index))
sWriter.Write(",")
sWriter.Write(password(index))
sWriter.Write(",")
sWriter.WriteLine(updatescore(position)
sWriter.Close()
MessageBox.Show("Writing file to disk")
Me.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
You cannot update a specific line in a text file. You can only rewrite a text file from scratch or append to it. Which is not what you want here.
You have to use File.ReadAllLines() to get a string[] with the lines in the text file. Search the specific element in the array that you want to update. Then write it all back with File.WriteAllLines().
This is expensive of course, but your text file is small. This is the primary reason why database engines are popular.
I see at least one additional bug in here (an exception would result in leaving the file open). You should do something like this instead:
fileName = "C:\Documents and Settings\Student\Desktop\Task10\primary4.txt"
Dim sWriter As IO.StreamWriter
Try
sWriter = New IO.StreamWriter(fileName, True)
index = lblPosition.Text
sWriter.Write(username(index))
sWriter.Write(",")
sWriter.Write(password(index))
sWriter.Write(",")
sWriter.WriteLine(updatescore(position)
MessageBox.Show("Writing file to disk")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
sWriter.Close()
End Try
Me.Close()