WebClient.DownloadFile convert to File VB.NET - vb.net

Does anyone know how to parse a Webclient.DowloadFile to File in VB.Net?
I'm currently using the following Code but I keep getting the errors:
(BC30491) Expression does not produce a value.
(BC30311) Value of Type can not be converted to File
Private Function DepartmentDataDownloader() As String
Dim webClient As New System.Net.WebClient
'I get here the error BC30491
Dim result As File = webClient.DownloadFile("https://intern.hethoutsemeer.nl/index2.php?option=com_webservices&controller=csv&method=hours.board.fetch&key=F2mKaXYGzbjMA4V&element=departments", "intern.hethoutsemeer.nl.1505213278-Departments.csv")
If webClient IsNot Nothing Then
'and here BC30311
Dim result As File = webClient
UploaderFromDownload(webClient)
End If
Return ""
End Function

The DownloadFile method doesn't return a value, because DownloadFile is a Sub. This is the reason why you get the BC30491 error. The second parameter specifies the path of the local file (and the result of the download).
So you can try something like the following:
Dim webClient As New System.Net.WebClient
'after this the file specified on second parameter should exists.
webClient.DownloadFile("https://intern.hethoutsemeer.nl/index2.php?option=com_webservices&controller=csv&method=hours.board.fetch&key=F2mKaXYGzbjMA4V&element=departments", "intern.hethoutsemeer.nl.1505213278-Departments.csv")
If webClient IsNot Nothing Then
'do something with the downloaded file (File.OpenRead(), File.*).
'Dim result As File
UploaderFromDownload(webClient)
End If
You also try to assign the WebClient value to a File variable. This is not possible so you get the BC30311 error.
Hint: You can't create an instance of the File class. The File class provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of FileStream objects.
source: https://learn.microsoft.com/en-us/dotnet/api/system.io.file

Related

Saving embedded resource contents to string

I am trying to copy the contents of an embedded file to a string in Visual Basic using Visual Studio 2013. I already have the resource (Settings.xml) imported and set as an embedded resource. Here is what I have:
Function GetFileContents(ByVal FileName As String) As String
Dim this As [Assembly]
Dim fileStream As IO.Stream
Dim streamReader As IO.StreamReader
Dim strContents As String
this = System.Reflection.Assembly.GetExecutingAssembly
fileStream = this.GetManifestResourceStream(FileName)
streamReader = New IO.StreamReader(fileStream)
strContents = streamReader.ReadToEnd
streamReader.Close()
Return strContents
End Function
When I try to save the contents to a string by using:
Dim contents As String = GetFileContents("Settings.xml")
I get the following error:
An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll
Additional information: Value cannot be null.
Which occurs at line:
streamReader = New IO.StreamReader(fileStream)
Nothing else I've read has been very helpful, hoping someone here can tell me why I'm getting this. I'm not very good with embedded resources in vb.net.
First check fileStream that its not empty as it seems its contains nothing that's why you are getting a Null exception.
Instead of writing to file test it by using a msgBox to see it its not null.
fileStream is Nothing because no resources were specified during compilation, or because the resource is not visible to GetFileContents.
After fighting the thing for hours, I discovered I wasn't importing the resource correctly. I had to go to Project -> Properties -> Resources and add the resource from existing file there, rather than importing the file from the Solution Explorer. After adding the file correctly, I was able to write the contents to a string by simply using:
Dim myString As String = (My.Resources.Settings)
Ugh, it's always such a simple solution, not sure why I didn't try that first. Hopefully this helps someone else because I saw nothing about this anywhere else I looked.

Cast FileInfo into FileSystemInfo

I am working on modifying file copy program that used to only copy a directory to another directory. Now I want to pass both directories and files in a list for the copy to run.
For Each _fromPath In CopyList
Dim FSinfo As FileSystemInfo()
If Directory.Exists(_fromPath) Then
Dim dir As New DirectoryInfo(_fromPath)
FSinfo = dir.GetFileSystemInfos
ElseIf File.Exists(_fromPath) Then
Dim file As New FileInfo(_fromPath)
FSinfo = file
End If
CountFiles(FSinfo)
Next
Private Function CountFiles(ByVal FSInfo As FileSystemInfo()) As Boolean
This code works fine for directories. In order to pass paths to the CountFiles, they must be in FileSystemInfo. Is there anyway to get FileInfo casted as a FileSystemInfo.
I tried CType(file, FileSystemInfo) but it said Value of type 'System.IO.FileInfo' cannot be converted to '1-dimensional array of System.IO.FileSystemInfo'.
One problem is that you are trying to convert an object (FileInfo) to an ARRAY of objects (FileSystemInfo()) which is what the error message is trying to tell you. You could write an overloaded function to handle some of that:
' my Count functions return numeric values:
Private Function CountFiles(FSInfo As FileSystemInfo()) As Integer
Private Function CountFiles(FInfo As FileInfo) As Integer
Internal to them, the FileSystemInfo might call the other in a loop to avoid duplicate code, or maybe they both call a common procedure depending on how it is written.

Deserializing in VB Without Failing When the File Does Not Exist

I've nicked some code from msdn to write and read to an xml file to persist my data, but I need a little help with it. I have a dynamic array called darr. As I understand it, I use this code to store it in an xml file:
Dim objStreamWriter As New StreamWriter("C:\temp\test.xml")
Dim x As New XmlSerializer(darr.GetType)
x.Serialize(objStreamWriter, darr)
objStreamWriter.Close()
And this to read it:
Dim objStreamReader As New StreamReader("C:\temp\test.xml")
darr = x.Deserialize(objStreamReader)
objStreamReader.Close()
The thing is, I want the app to read from the file on startup, which means the second block gets called first and if the file doesn't exit yet, it throws an exception. (The first block automatically creates the file if not found.) So two questions:
Is there a way to have the app create the file automatically the first time it runs?
Since the file will be empty... will the code work? If not, is there a workaround? (Okay that's three questions!)
If Not File.Exists("C:\temp\test.xml") Then
' Create the file.
Dim file As System.IO.FileStream
file = System.IO.File.Create("C:\temp\test.xml")
Else
Dim objStreamWriter As New StreamWriter("C:\temp\test.xml")
Dim x As New XmlSerializer(darr.GetType)
x.Serialize(objStreamWriter, darr)
objStreamWriter.Close()
End If

How do I output to a text file without getting an IO exception?

I have this code.
Dim txtVern As String = String.Empty
Try
Using verSR As New StreamReader(appDataVersionLoc)
txtVern = verSR.ReadToEnd()
End Using
Catch ex As Exception
Dim verFile As System.IO.FileStream
verFile = System.IO.File.Create(appDataVersionLoc)
Dim wWFERes As DialogResult = MessageBox.Show("Version file missing/corrupt, created a new one.")
If My.Computer.FileSystem.FileExists(appDataVersionLoc) Then
My.Computer.FileSystem.WriteAllText(appDataVersionLoc, "0.0.0.0", True)
End If
End Try
But when it tries to execute My.Computer.FileSystem.WriteAllText(appDataVersionLoc, "0.0.0.0", True), I get this error:
The process cannot access the file 'C:\Users\Dubstaphone\AppData\Roaming\TheArena\version.txt' because it is being used by another process.
How to I avoid this? What I did was I made it create a text file called "version.txt" if it doesn't already exist. Now I'm trying to write "0.0.0.0" to it, but it's giving me that error. By the way, "appDataVersionLoc" equals GetFolderPath(SpecialFolder.ApplicationData) & "\TheArena\version.txt"
This variable works fine for everything else.
Thanks!
P.S.
I'm a complete noob.
System.IO.File.Create or My.Computer.FileSystem.WriteAllText may still hold a lock on the file. Use the System.IO.File WriteAllText and a Using statement.
If you use a Stream you should close/dispose of it. Better yet when dealing with files always use a Using statement.
Edit:
Example of creating a file
Using File.Create(path)
End Using
If File.Exists(appDataVersionLoc) Then
File.WriteAllText(appDataVersionLoc, "0.0.0.0")
End If
or
Dim appDataFile = File.Create(path)
appDataFile.Close

How to avoid file is being used by another process in vb.net

I am trying to check whether file exists or not. if not create and write something into it. The file is getting created but not updating and getting error message says it is being used by another process
Code snippet:
Public shared sub MyXml()
If Not System.IO.File.Exists("configfile.xml") Then
Dim writer As New System.Xml.XmlTextWriter(fullPath.ToString + "\configfile.xml", Nothing)
End If
Dim xmlElement As New XElement("FilePath", ConfigWindow.Datapath.Text)
System.IO.File.WriteAllText(fullPath + "\configfile.xml", xmlElement.ToString())
end sub()
Any suggestions please...
WriteAllText will create the file, so you can simply remove the If statement:
Public Shared Sub MyXml()
Dim xmlElement As New XElement("FilePath", ConfigWindow.Datapath.Text)
System.IO.File.WriteAllText(fullPath + "\configfile.xml", xmlElement.ToString())
End Sub
The reason the file is locked is that your code creates an XmlTextWriter that is not disposed, so it keeps holding on to the file.