Download file from FTP without caching in VB.NET - vb.net

I know there are several solutions in other languages but I can't find anything in VB.NET.
I have a file containing the "software version" on an FTP server, however everytime the program tries to read it through the WebBrowser, it picks up an old version of it. In other words the cached version.
Is there anything that can use to clear the cache for just the one file?
Code so far:
Dim WebBR As New WebBrowser
WebBR.Navigate("URL\Version.txt", False)
Do Until WebBR.ReadyState = WebBrowserReadyState.Complete
Application.DoEvents()
Loop
Dim VRB = WebBR.Document.Body.InnerHtml
VRB = VRB.Replace("<PRE>", "")
VRB = VRB.Replace("</PRE>", "")
NewVersion = VRB
If NewVersion <> CurrentVersion Then
Return True
Else
Return False
End If

Why do you read the file though web browser? That's an overkill.
Use the FtpWebRequest. It does not have any cache.
See also:
Upload and download a binary file to/from FTP server in C#/.NET
How to: Download Files with FTP.

Related

Download many small files with FTP quickly

I have a working code to download many files (hundreds) from an FTP server, but it's very slow and often a timeout error appears.
This is my current way of doing the downloads:
Using ftpClient As New WebClient()
ftpClient.Credentials = New System.Net.NetworkCredential(ftpuser, ftppassword)
For i As Integer = 0 To directoriesDownload.Count - 1
If directoriesDownload(i).Contains(".") Then
If Sync_BackgroundWorker.CancellationPending = True Then
Exit Sub
End If
Dim path As String = "ftp://" & ftpserver & "Datenbank/" + directoriesDownload(i).ToString()
Dim trnsfrpth As String = config.rootpath & "ServerDownload\" + directoriesDownload(i).ToString()
ftpClient.DownloadFile(path, trnsfrpth)
filenametodownload = directoriesDownload(i).ToString()
filesdownloaded += 1
Sync_BackgroundWorker.ReportProgress(filesdownloaded)
End If
Next
ftpClient.Dispose()
End Using
Is there any faster way of downloading hundreds of small files (up to 10 KB) from an FTP server in VB.NET?
It would be the best if there is an option to sign into the FTP only once instead of logging in and out for every file.
I found somebody else having the same problem but without a working result:
Using FTP to download each file *WHILE* getting the file list
I also tried multithreading with a Parallel.For loop, but WebClient does not work with multithreading. Same thing if I try with ftpClient.DownloadFileAsync(New Uri(path), trnsfrpth).
Is there any faster way of downloading hundreds of small files (up to 10 KB) from an FTP server in VB.NET?
...
I also tried multithreading with a Parallel.For loop, but WebClient does not work with multithreading. Same thing if I try with ftpClient.DownloadFileAsync(New Uri(path), trnsfrpth).
Multithreading is the way to go. It's not true that WebClient does not support multithreading. Why wouldn't it?
If you have a problem with implementing multithreaded FTP transfers, you should ask a question about that, rather than asking a question about other (and probably non-existent) ways.
It would be the best if there is an option to sign into the FTP only once instead of logging in and out for every file.
Your code does sign into FTP only once.
See C# - FtpWebRequest - Multiple requests over the same connection/login - What is written there about FtpWebRequest is equally true for WebClient, as WebClient uses FtpWebRequest internally.

Program not able to write to a newly made text file

After some great arguments made by other users in this question: How to write to a text file inside of the application, I decided to not use a resource file, instead create a file in a folder & then read/write from there.
Although, for some reason, I can't seem to write to the file in question, it keeps throwing an exception telling me the file is already in use by another process.
Here's the code which I use for writing to this file.
If System.IO.File.Exists(credentials) Then
Dim objWriter As New System.IO.StreamWriter(credentials, False)
objWriter.WriteLine(remember)
objWriter.Close()
Else
System.IO.Directory.CreateDirectory(Mid(My.Application.Info.DirectoryPath, 1, 1) & ":\ProgramData\DayZAdminPanel")
System.IO.File.Create(credentials)
Dim objWriter As New System.IO.StreamWriter(credentials, False)
objWriter.WriteLine(remember)
objWriter.Close()
End If
Any ideas on how I can write to the text file in question?
There's a good chance that a previous iteration of your application failed to properly close access to the file in the StreamWriter. Since your constructor is set to overwrite (and not append) to the file, this could be the source.
Try setting up your application with a "Using" statement to properly open/close the file:
If System.IO.File.Exists(credentials) Then
Using objWriter As StreamWriter = New StreamWriter(credentials, False)
objWriter.WriteLine(remember)
objWriter.Close()
End Using
Else
System.IO.Directory.CreateDirectory(Mid(My.Application.Info.DirectoryPath, 1, 1) & ":\ProgramData\DayZAdminPanel")
System.IO.File.Create(credentials)
Using objWriter As StreamWriter = New StreamWriter(credentials, False)
objWriter.WriteLine(remember)
objWriter.Close()
End Using
End If
It does look rather redundant to have a Using block and a close statement, but this ensures access to your file even if an exception occurs.
You are trying to create a directory in the common application data directory. This directory should be found using the Environment class methods and enums because is different between operating systems. However you use the value credentials for the filename. I suppose that you want to store your datafile in the common application directory and not in a place where there is no permission to write data files (Like C:\program files (x86)).
Then, to avoid problems with file stream not correctly closed try to use the Using statement that assures a correct closure and disposal of your file resource (No need to call close inside a Using).
Also, notice that StreamWriter is perfectly capable to create the file if it doesn't exists or if you wish to overwrite the previous contents (passing false for the Append flag).
So your code could be reduced to these lines.
' Get the common application data directory (could be different from Win7 and XP)
Dim workDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
' Combine with your own working data directory
workDir = Path.Combine(workdir, "DayZAdminPanel")
' Create if not exists
If Not Directory.Exists(workDir) Then
Directory.CreateDirectory(workDir)
End If
' Create/Overwrite your data file in a subfolder of the common application data folder
Dim saveFile = Path.Combine(workDir, Path.GetFileName(credentials))
Using objWriter = New System.IO.StreamWriter(saveFile, False)
objWriter.WriteLine(remember)
End Using
File.Create returns an opened FileStream that you should be passing into the StreamWriter constructor on the subsequent, rather than passing the filename again, or you can just omit the File.Create call altogether.
You might want to look into a Using block for the StreamWriter so it gets predictably closed.

VB.Net File.Exists() Returns True but Excel cannot Open

I check for the existence of the file with File.Exists(filePath). Then I try to open the file from within Excel with Excel.Workbooks.OpenText(filePath). But Excel complains that the file's not there. What the heck?
The context is that I am shelling out to another application to process a given file and produce a .out file, which I then convert to an Excel workbook.
'' At this point, filePath is a .txt file.
Dim args As String = String.Format("""{0}""", filePath)
...
Dim exe As String = Config.ExtractEXE
Dim i As New ProcessStartInfo(exe)
i.Arguments = args
Dim p As Process = Process.Start(i)
p.WaitForExit()
...
'' filePath now becomes the .out file.
'' Then eventually, I get around to checking:
'If Not File.Exists(filePath) Then
' MsgBox("Please ensure...")
' Exit Sub
'End If
'' In response to an answer, I no longer check for the existence of the file, but
'' instead try to open the file.
Private Function fileIsReady(filePath As String) As Boolean
Try
Using fs As FileStream = File.OpenRead(filePath)
Return True
End Using
Catch
Return False
End Try
End Function
Do Until fileIsReady(filePath)
'' Wait.
Loop
ExcelFile.Convert(filePath...)
'' Wherein I make the call to:
Excel.Workbooks.OpenText(filePath...)
'' Which fails because filePath can't be found.
Is there a latency issue, such that .Net recognizes the existence of the file before it's accessible to other applications? I just don't understand why File.Exists() can tell me the file is there and then Excel can't find it.
As far as I know, the only application that might have the file open is the application I call to do the processing. But that application should be finished with the file by the time p.WaitForExit() finishes, right?
I've had to deploy the application with this as a known bug, which really sucks. There's an easy workaround for the user; but still--this bug should not be. Hope you can help.
Whether or not a file exists is not the only factor in whether you can open it. You also need to look at file system permissions and locking.
File.Exists can lie to you (it returns false if you pass a directory path or if any error occurs, even if the file does exist)
The file system is volatile, and things can change even in the brief period between an if (File.Exists(...)) line and trying to open the file in the next line.
In summary: you should hardly ever use file.exists(). Almost any time you are tempted to do so, just try to open the file and make sure you have a good exception handler instead.

the process cannot access the file because it is being used by another process in vb.net

help me.. i'm new in visual basic....
when i'm running the update it shows the error
The process cannot access the file 'C:\Documents and Settings\Macky\My Documents\Visual Studio 2008\Projects\Marcelo 2.2.3\Marcelo\bin\Debug\Students\MIC953867.jpg' because it is being used by another process.
my code is this
Public Sub copingfile()
If inFileName = Nothing Then
studpic.Image = Nothing
Else
outFileName = inFileName
pos = inFileName.LastIndexOf(".")
If (pos > 0) Then
outFileName = outFileName.Substring(0, pos)
End If
outFileName += ".jpg"
str = Application.StartupPath & "\Students\"
saveJPEGFile.FileName = str & StudID.Text & ".jpg" '& outFileName
fil1.Copy(inFileName, saveJPEGFile.FileName, True) 'the error shows here...
outFileName = saveJPEGFile.FileName()
End If
End Sub
I can save new student information with picture.. but when it comes in updating the picture these codes didn't work......
fil1.Copy(inFileName, saveJPEGFile.FileName, True)
You're attempting overwrite a file that's open or being used. If the file is open in a viewer/editor, then it can't be copied over. Either you opened it manually, or did so through code and it's still "attached" to something running.
If it's not open in a window, try stopping your code and deleting that file manually. If you can, it's pretty obvious something in code is still using it when you get to the line that errored. You'll need to figure out where that file is still being used (Open stream somewhere? Open in VS, itself?), as it doesn't appear to be in the code you provided.
You are going to need to show more code, you are using variables not in your code listing. Plus you do not show the code that originally saves your image.
But here is my guess...are you sure you closed the file when you saved it for the first time? You cannot generally copy to, or from, a file that is open.
(Files can be opened as shared, but I don't think you are doing that).
Post more code if you get a chance.

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