Cannot write to a file after reading it with IO.StreamReader - vb.net

I am making an encryption program that also functions as a notepad (CryptoMatic). There is a Open function with the following code:
Dim r As New StreamReader(filename)
Dim text As String = r.ReadToEnd
txtFileContents.text = text
r.Dispose()
r.Close()
Now there is the save and save as button
the save button checks if the file had been saved previously or not. If yes then I am trying to write to that file with the following code:
Dim myFileStream As New System.IO.FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.None)
myFileStream.Lock(0, 100)
Dim myWriter As New System.IO.StreamWriter(myFileStream)
myWriter.WriteLine(text)
myWriter.Flush()
myWriter.Close()
myFileStream.Close()
myFileStream.Unlock(0, 100)
Now when i press the save button it gives the following error:
The process cannot access the file 'C:\Users\VisualTech\Documents\Visual Studio 2010\Projects\CryptoMatic Update\CryptoMatic Update\bin\Debug\text.txt' because it is being used by another process.
and the application stops, can anyone please help me?

I have tried your code above and have noticed two things:
You don't need a myFileStream.Lock call because you already open it
with FileShare.None
You can't call myFileStream.Unlock(0, 100) after the call to
myFileStream.Close()
So I have rewritten your code in this way.
Sub Main
Dim text = "This is a text to write in the stream"
Using myFileStream As New System.IO.FileStream("D:\temp\testlock.txt", FileMode.Append, FileAccess.Write, FileShare.None)
Using myWriter As New System.IO.StreamWriter(myFileStream)
myWriter.WriteLine(text)
End Using
End Using
End Sub

Related

Unable To Read Text File Because Its Open By Another Process VB.Net

I am having problems trying to read a text file which is open by another process.
After searching SO I have found a few similar questions albeit in C# and nor VB.Net which seem to refer to the fact that FileShare.ReadWrite is the key to getting this to work but yet I am still struggling with it.
This is what I have so far but nothing is appearing in TextBox1.
Dim logFileStream As FileStream = New FileStream("C:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim logFileReader As StreamReader = New StreamReader(logFileStream)
While Not logFileReader.EndOfStream
Dim line As String = logFileReader.ReadLine()
TextBox1.Text = line
End While
logFileReader.Close()
logFileStream.Close()
My goal is to just use the last 2 lines of what's in the file c:\test.txt and display those contents into a Label but I guess I first need to read and show the content before I can start to look at just extracting the last 2 lines.
Update:
After re-visiting the MS Docs, I have rearranged the code as below and I can now seem to read the open file into a TextBox
Dim strLogFilePath As String
Dim LogFileStream As FileStream
Dim LogFileReader As StreamReader
Dim strRowText As String
strLogFilePath = "C:\DSD\DSDPlus.srt"
LogFileStream = New FileStream(strLogFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
LogFileReader = New StreamReader(LogFileStream)
strRowText = LogFileReader.ReadToEnd()
TextBox1.Text = strRowText
LogFileReader.Close()
LogFileStream.Close()

How to download file from SFTP in vb.net

I am trying to use the classes in Renci.SshNet.Sftp to download a file from an SFTP server with VB.NET. Here is my code:
Using client As New SftpClient("server", "test", "test")
client.Connect()
Dim list As List(Of SftpFile) = CType(client.ListDirectory(""), List(Of SftpFile))
'------------------------
For Each sFile As SftpFile In list
Console.WriteLine(sFile.Name)
client.DownloadFile("path", ????)
Next
client.Disconnect()
End Using
With this code I can connect to the server and see the file, but I can't download it. I don't know how to call the DownloadFile method.
The second parameter of the DownloadFile method takes a stream. So, you just need to create a new FileStream to write the downloaded data to a new file, like this:
Using fs As New FileStream(localFilePath, FileMode.CreateNew, FileAccess.Write)
client.DownloadFile(serverFilePath, fs)
End Using

Null Reference Exception when reading file vb.NET

So I am creating a program that needs to be able to read line by line from a .cfg (config) file, it can open it happily; here is the code:
OpenConfig.ShowDialog()
file = OpenConfig.FileName()
fileReader()
However when it tries to read the file, using this code:
Function fileReader()
Dim reader As New StreamReader(file)
Dim vLb As ListBox = shopTabs.SelectedTab.Controls.Item(10) 'Listbox Variable
For i = 0 To reader.Peek
textline(i) = reader.ReadLine()
vLb.Items.Add(i)
Next
Return True
End Function
It throws an exception at the line:
textline(i) = reader.ReadLine()
Any help would be greatly appreciated as I can't work out why it does so.
Your code could be simplified into the following code:
Using openConfig As New OpenFileDialog()
If openConfig.ShowDialog(Me) = DialogResult.OK Then
For Each s As String In File.ReadAllLines(openConfig.FileName)
ListBox1.Items.Add(s)
Next
End If
End Using
As I commented, your code does some things that are highly questionable and undoubtedly difficult to maintain, such as referencing a control by the index property.
I suspect that your project would benefit from using UserControls too, since I'm guessing you have the same controls placed in every tab (a ListBox is always control index #10?).

AxAcroPdf Control - Issues reloading PDF

When using the axAcroPdfLib.AxAcroPDF control in my Windows Forms application, I'm not able to reload the same image. The image is initially loaded with the LoadFile() method.
Upon using the LoadFile() method again on the same path AFTER saving changes to the PDF, the control becomes blank (no PDF shown).
If I set the src property of the control to the path, I get a message saying the file does not begin with '%PDF-'. But it does. I opened it with Word and it clearly begins with %PDF-. It's not corrupt or locked either.
I've even tried closing, disposing, or setting it to Nothing, and then completely re-instantiating it as I did the first time it's loaded - no effect. The window closes and shows with the control blank.
Loading a different file via the above methods has the same effect - blank.
Using Windows 7 64-bit, VS 2010, VB.NET.
The code is below. For right now, I'm just trying to draw a simple line on it.
Private Sub _btnBarCode_Click(ByVal sender As Object, ByVal e As EventArgs) Handles _btnBarCode.Click
Dim pdfReader As iTextSharp.text.pdf.PdfReader = Nothing
Try
pdfReader = New iTextSharp.text.pdf.PdfReader(File.ReadAllBytes(_path))
Using fs As New FileStream(_path, FileMode.Create, FileAccess.Write)
Using pdfStamper = New iTextSharp.text.pdf.PdfStamper(pdfReader, fs)
Dim pdfPage As iTextSharp.text.pdf.PdfContentByte = pdfStamper.GetOverContent(1)
Using barCodeForm As New FBarCode
barCodeForm.Barcode = _barCode
If (barCodeForm.ShowDialog(Me) = DialogResult.OK) Then
Dim screenBarCode As Point = barCodeForm.Location
Dim clientBarCode As Point = Point.op_Subtraction(PointToClient(screenBarCode), New Point(0, 50)) '_pdfControl.Location '_imgView.Location
clientBarCode = New Point(10, 50)
Dim barcodeImg As New Bitmap(200, 50)
Using gc As Graphics = Graphics.FromImage(barcodeImg)
gc.DrawLine(Pens.Red, New Point(10, 10), New Point(20, 20))
'barCodeForm._barCode.DrawBarCode(gc, clientBarCode)
End Using
Dim convert As ImageConverter = New ImageConverter()
Dim bmpBytes As Byte() = DirectCast(convert.ConvertTo(barcodeImg, GetType(Byte())), Byte())
Dim thisImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(bmpBytes)
thisImage.SetAbsolutePosition(clientBarCode.X, clientBarCode.Y)
thisImage.SetDpi(72, 72)
pdfPage.AddImage(thisImage)
rdrAdobePdf.LoadFile(_path) 'Blank pdf
'rdrAdobePdf.src = _path '"Does not begin with '%PDF-' (even though it does)
'Me.Close()
'_myParent.ResetPdfViewer()
'ReloadPdfViewer(Me.Barcode)
End If
End Using
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message, "An error occurred.")
Return
Finally
If Not pdfReader Is Nothing Then pdfReader.Close()
End Try
End Sub
Any ideas what could be the problem here?
Problem was solved by getting the reloading code out of that click method. Putting it in another click method solved the problem - not sure why. The code I used just ran .LoadFile, then Form.Show() and Form.Activate().

Strange "IOException was unhandled"

(VB.NET, .NET 3.5)
I wrote the following function to read some text from txt file. It was working fine but now it's not. It keeps giving me this error message
"IOException was unhandled" and
" The process cannot access the file 'F:\kh_matt\ch1.txt' because it is being used by another process."
The ch1.txt is not even opened or being used by any program at all. I tried to move ch1.txt to another location (Drive D) still I got the same message error but just different location it says The process cannot access the file 'D:\ch1.txt' because it is being used by another process."
Here's my code block :
Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click
Dim reader As StreamReader
Dim filelocation As String
filelocation = "F:\kh_matt\ch1.txt"
Dim chid As Integer
chid = 1
If System.IO.File.Exists(filelocation) = True Then
reader = New StreamReader(New FileStream(filelocation, FileMode.Open))
Else
MsgBox(filelocation, MsgBoxStyle.OkOnly)
End If
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
Dim vArray() As String = MyStream.ReadToEnd.Split(CChar("$"))
MyStream.Close()
Dim count As Integer
For d As Integer = 0 To vArray.Length - 1 Step 1
If d = vArray.Length - 1 Then
Exit For
End If
InsertKh(chid, d + 1, vArray(d))
count = d + 1
Next
MsgBox("Done Inserting")
End Sub
It always points to this code :
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
Where I debug and press the respective button. Can anyone point out what the problem is ? Thanks
I think this is your problem:
If System.IO.File.Exists(filelocation) = True Then
reader = New StreamReader(New FileStream(filelocation, FileMode.Open))
If the file exists it will open a StreamReader on it, then try and open another StreamReader on the same file, which will lock the file, causing this line:
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
to fail.
Also, some pointers:
consider using the System.IO.File.ReadAllText() method instead, much easier
if you must use streams, wrap them in a using block to ensure they're freed correctly, for example:
`
Dim vArray() As String
using (Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
{
vArray = MyStream.ReadToEnd.Split(CChar("$"))
}
(sorry if the above code isn't 100% correct, I don't write much VB.Net)
It seems you open the file twice, which is probably what's causing your error:
reader = New StreamReader(New FileStream(filelocation, FileMode.Open))
...
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
Are you sure that's what you intend to do? It looks like you can remove MyStream and use reader instead. Also, you don't have to use Path.Combine, since filelocation is not relative.
Make sure that you close your stream & streamreader once you've finished reading the file, even when an exception is being thrown.
Use a try/finally block, and close the stream / streamreader in the finally block.
Thanks all for the reply. It's my mistake. I forgot to comment out my code that I wrote for testing earlier. After commenting this code out it works like before.
'If System.IO.File.Exists(filelocation) = True Then
' reader = New StreamReader(New FileStream(filelocation, FileMode.Open))
'Else
' MsgBox(filelocation, MsgBoxStyle.OkOnly)
'End If
Have a good day.