Access to .txt [VB.NET] - vb.net

I've developed a multi-user application. One user saves a string to a text file, other users have to read this string in a background process.
My problem is: when some users open the file to read the string, another user that wants to save a new string can't write to the file. I would like to implement a system that checks if the file is opened or not, and in case it is, waits a few seconds and retries.
What is the function or command to look if the file is already opened?

I solved my problem using tips:
i've replaced this code:
ip_acquisito = My.Computer.FileSystem.ReadAllText(path_elenco & "\ip.txt")
with this code:
Using fs As FileStream = File.Open(path_elenco & "\ip.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim b(1024) As Byte
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Do While fs.Read(b, 0, b.Length) > 0
ip_acquisito = temp.GetString(b)
Loop
End Using

There are quite a few patterns you can deal with. Two I'd recommend would be:
Dealing with FileAccess, FileMode and FileShare
Sync the file access with EventWaitHandle

Related

Cloning a csv file to memory and using it in a datatable? (vb.net)

I have a question about the following code. in order to prevent problems caused by file locking I came across the following code.
Dim OrignalBitmap As New Bitmap(Application.StartupPath & "\IMAGES\BACKGROUND_LARGE.jpg")
Dim CloneBitmap As New Bitmap(OrignalBitmap)
OrignalBitmap.Dispose()
Which works like a charm. Now I have all the images in place and I can still access them as a file without anything locking. It works so well for what I need that I was thinking if its possible to do this for file formats other than images such as Csv files which are then used in a datagridview as a bound table?
Usually it is enough to open a File like this, so that it will not block other programs to access and open it.
Dim path1 As String = "C:\temp\temp.csv"
Using fs As FileStream = File.Open(path1, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
' Do something with filestream
End Using
this will prevent even huge files to open without blocking access
you should check https://learn.microsoft.com/de-de/dotnet/api/system.io.file.open?view=netframework-4.8

Can't open IIS w3c log vb.net

I have been writing an app in vb.net to copy the last few lines of an IIS W3C log file every few minusts to A file that will be used for some remote reporting.
Everything works when I test on my local PC but when I try it on the live IIS server it tells me the file is locked by another process, I take it IIS has it locked...
It does read in some of the sites log files (more than on site on the server) but not others, tells me locked/in use.
Why is it that I can always open the file in notepad but not open it in my app?
The Code:
Dim linex = ""
Dim Line = ""
'### IT ERROS OUT ON THE NEXT LINE ###
Using sr As New StreamReader("C:\inetpub\logs\LogFiles\W3SVC14\u_ex130702.log")
Do Until sr.EndOfStream
linex = sr.ReadLine()
line = line & linex & vbCrLf
Loop
End Using
You need to specify correct sharing options and open mode when creating underlying FileStream. Since there is no constructor of StreamReader that passes all necessary arguments you need to construct FileStream first using FileStream(String, FileMode, FileAccess, FileShare) and than create StreamReader on it using SrteamReader(Stream).
I think following should open IIS log file while it is being written to by IIS (if not - try other combinations of flags)
Using stream As New New FileStream( _
"Test####.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Using sr As New StreamReader(stream)

Making a back up of A SQL Server Compact Edition Corrupts the database

On close of an application written in VB, I need to copy the .sdf file, this is the local SQL Server CE database that syncs with the server. Each time we close the app we require a backup to be made.
I am using the file.copy method. First I close the connection to the database then copy the file to a specific location.
Dim conn As SqlCeConnection = New SqlCeConnection(My.Settings.MyClientConnectionString)
conn.Open()
conn.Close()
Dim tpath As String = My.Settings.CertPath
Dim path As String = tpath.Replace("db\", "MyDatabase.sdf")
Dim fs As FileStream = File.Create(path)
fs.Close()
File.Delete("C:\db\backup\MyDatabase.sdf")
File.Copy(path, "C:\db\backup\MyDatabase.sdf")
The problem arises on the line of code:
Dim fs As FileStream = File.Create(path)
The database becomes corrupted and has a size of 0 kb.
Has anyone seen this before? Thanks
Are you calling Create on an existing database file? According to the docs, Create creates or overwrites a file in the specified path. In the code you show, calling Create isn't necessary anyway. Just call File.Copy.

Loading Sequential Files in VB

I have written a vb program a few years ago and now as I get started with vb again i am hitting a "snag". With sequential files. I am trying to load a file in to the vb program with the file dialog box.
NOTE:I am using structures
Dim FileDialog as new openFileDialog
Dim MyStream as Stream = nothing
Dim FileLocation as string 'this is to save the file location
if( FileDialog.ShowDialog() = DialogResults.OK)Then
FS = new FileStream(FileLocation, FileMode.open, fileaccess.Read)
BF = new BinaryFromatter
While FS.Position < FS.Length
Dim temp as unit
...'Please note that this is where the file reads the structures data.It is to much code to write in.
When I run the program I can create a file and save it with the data in and I can load it with the Dialog box, The problem is when I run the program again and try to load it. It just wont run the file or load it(Remember I created the file with this program and saved)
How do I get this to work?
Make sure you have closed the file after writing and reading the data the first time, and make sure you are using the correct path (FileLocation).
Exit Visual Studio between the first and second times you run the program. If it works then, then you know you are not closing the file properly.
Set a breakpoint at the new FileStream assignment and check the value of FileLocation. Is it the same as it was when the file was written?
Check the error message, if there is one, and see if that tells you anything.

Not sure how to use IsolatedStorage

I want to create a notes app for Windows Phone 7 using Visual Basic. I have read a few tutorials but they are all suited for C# not VB. Basically, I have a main page and a page to add notes. Once the user types out a note on the add notes page, the title of that note appears on the main page. I also want the user to be able to select that title and it will display the note. I have done a bit of research and I know I will need to use isolated storage (not sure how to implement it in VB) to save the notes. I think I will also need a list box that will store the title of the notes. I am not asking for someone to just give me code, I am asking for some tutorials regarding this in VB or any pointers or general help on acheiving this. Thanks
All the code samples on MSDN are available in both C# and VB. See http://msdn.microsoft.com/en-us/library/ff431744(v=vs.92).aspx
The Model-View-ViewModel Sample (under Common Application Development Tasks) is probably a good place for you to start.
The link to download the VB code is http://go.microsoft.com/fwlink/?LinkId=229339
You are correct that you will need to use IsolatedStorage if you're wanting to write the notes to the phone (and not the cloud somewhere). Here is a link to a blog entry that has a class (in Visual Basic) that has some helper methods that will give you some similiar methods to VB.Net traditional methods (like ReadAllText, WriteAllText). It may be what you want for the file system reading/writing (but at a minimum will get you started with Isolated Storage).
http://www.blakepell.com/2012-03-07-wp7-file-helpers
Isolated Storages
Isolated storage is used to store local files such as text files, images, videos etc on the Windows Phone. Each app is assigned a specific isolated storage and is exclusive ONLY to that app. No other app is able to access your apps isolated storage.
A lot can be read from here All about Windows Phone Isolated Storage
Before you begin you will need to import IsolatedStorage to your project.
Imports System.IO
Imports System.IO.IsolatedStorage
Creating Folders
This creates a directory in your apps isolated storage. It will be called "NewFolder"
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
myIsolatedStorage.CreateDirectory("NewFolder")
You can create folders inside folders inside folders like so:
myIsolatedStorage.CreateDirectory("NewFolder/NewFolder1/NewFolder2/NewFolder3")
To delete a folder:
myIsolatedStorage.DeleteDirectory("NewFolder")
A good practice when creating and deleting folders is to add a Try Catch statement around the folder creation method so if there is an exception you or the user will be notified as to why it occurs e.g. the folder not existing therefore cannot be deleted or the folder existing therefore needing to be replaced etc. The example below shows a basic function in creating a folder with a Try Catch statement.
Public Sub CreateDirectory(directoryName As String)
Try
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
If Not String.IsNullOrEmpty(directoryName) AndAlso Not myIsolatedStorage.DirectoryExists(directoryName) Then
myIsolatedStorage.CreateDirectory(directoryName)
End If
' handle the exception
Catch ex As Exception
End Try
End Sub
To use it you can do:
Me.CreateDirectory("NewFolder")
For the deletion method:
Public Sub DeleteDirectory(directoryName As String)
Try
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
If Not String.IsNullOrEmpty(directoryName) AndAlso myIsolatedStorage.DirectoryExists(directoryName) Then
myIsolatedStorage.DeleteDirectory(directoryName)
End If
' handle the exception
Catch ex As Exception
End Try
End Sub
And to use it:
Me.DeleteDirectory("NewFolder")
Creating Files
You can create an empty file like this:
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Dim writeFile As New StreamWriter(New IsolatedStorageFileStream("NewFolder\SomeFile.txt", FileMode.CreateNew, myIsolatedStorage))
To delete the file:
myIsolatedStorage.DeleteFile("NewFolder/SomeFile.txt")
Like before, a good practise when it comes to creating files is to always check if the directory you are writing to or deleting exists.
You can do something like:
Try
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Dim writeFile As StreamWriter
If Not myIsolatedStorage.DirectoryExists("NewFolder") Then
myIsolatedStorage.CreateDirectory("NewFolder")
writeFile = New StreamWriter(New IsolatedStorageFileStream("NewFolder\SomeFile.txt", FileMode.CreateNew, myIsolatedStorage))
Else
writeFile = New StreamWriter(New IsolatedStorageFileStream("NewFolder\SomeFile.txt", FileMode.CreateNew, myIsolatedStorage))
End If
' do something with exception
Catch ex As Exception
End Try
Saving and Reading Text Files
To save a text file with your content you can do something like:
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Using writeFile As New StreamWriter(New IsolatedStorageFileStream("myNote.txt", FileMode.Create, FileAccess.Write, myIsolatedStorage))
Dim someTextData As String = "This is some text data to be saved in a new text file in the IsolatedStorage!"
writeFile.WriteLine("note data")
writeFile.Close()
End Using
To read the contents of the Text File:
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Dim fileStream As IsolatedStorageFileStream = myIsolatedStorage.OpenFile("myFile.txt", FileMode.Open, FileAccess.Read)
Using reader As New StreamReader(fileStream)
TextBlock.Text = reader.ReadLine()
End Using
I've provided you with some of the basics of the Windows Phone Isolated Storage and how to use it but I highly suggest that you read more about it at Here