I have looked almost everywhere on the internet and I cannot find a way to download a file from the internet into a specific folder that works with VB.NET 2010. I would like to download a file called, for instance, example.txt, and download it into, for example, %HOMEDRIVE%%HOMEPATH%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup so that it will run automatically at system startup. All help is appreciated
Guessing something based on...
Using webClient = New WebClient()
Dim bytes = webClient.DownloadData("http://www.google.com")
File.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyFileName.ext"), bytes)
End Using
As for the startup, VB.NET has a pretty ease way to add Registry keys...
My.Computer.Registry.SetValue
To set something like HKEY_CURRENT_USER\Software\Microsoft\CurrentVersion\Run
UPDATE
How to: Create a Registry Key and Set Its Values in Visual Basic
http://msdn.microsoft.com/en-us/library/cy6azwf7(v=VS.100).aspx
I would suggest using WebClient.DownloadFile. Use Environment.SpecialFolder.Startup to get the path to save the file.
Sub Main()
Using wc As New WebClient()
Dim startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
wc.DownloadFile("http://MyDomain.com/MyFile.txt", Path.Combine(startupPath, "test.txt"))
End Using
End Sub
Related
I am using the below code to navigate to a specific web address as follows :
WebBrowser1.Navigate("http://192.168.0.157/cm?cmnd=POWER%20Toggle"
The fact is that the the link returns a .json file and the WebBrowser controls displays the default save file dialog asking if i want to save the file or run it.
I want to ignore it the dialog and read from the .json file directly(i mean after downloading it).
I just want to get rid of the Save dialog of the webbrowser.I am a newbie so i don't know what to search or how to ask properly.
Though your post is not even close to be standard and hardly explains the issue, what i understand so far is that you have a few issues and i will answer them separately.
Disabling the download dialog of the webbrowser and downloading the files automatically
Firstly, you mentioned it returns a .json file. So , you can easily add a SaveFileDialogto your form or set a custom path(maybe in a variable) and check if the webbrowser is trying to download any .json files. Then you will Cancel the call(typically i mean that cancel the popup that says Save , Run ...) and make use of the SaveFileDialog or the local variable to save the file directly to disk. Here's a sample which uses a local string variable as the path and saves the .json file directly to disk :
Imports System.ComponentModel
...
Dim filepath As String '''class lever variable
Private Sub myBroswer_Navigating(sender as Object, e As WebBrowserNavigatingEventArgs) Handles myBroswer.Navigating
If e.Url.Segments(e.Url.Segments.Length - 1).EndsWith(".json") Then
e.Cancel = True
filepath = "C:\test\" + e.Url.Segments(e.Url.Segments.Length - 1)
Dim client As WebClient = New WebClient()
AddHandler client.DownloadFileCompleted , AddressOf New AsyncCompletedEventHandler(DisplayJson);
client.DownloadFileAsync(e.Url, filepath)
End If
End Sub
Displaying the result AKA .json
It is very easy to de-serialize/parse .json files.But first, download this , extract the ZIP and Add Reference to Newtonsoft.Json.dll. Now consider the bellow code snippet :
Private Sub DisplayJson()
Dim parseJson = Newtonsoft.Json.Linq.JObject.Parse(File.ReadAllLines(filepath))
MsgBox(parseJson("element name here").ToString)
End sub
Hope this helps
In my VB.net application I am opening a PDF file using
System.Diagnostics.Process.Start("c:\TEMP\MyFile.pdf").
Is it possible to Close this file Programatically in some event.
Yes, there is one way, though it is not a very elegant solution.
When you start the PDF process, you capture the process-id in some global variable:
Dim id As Integer 'Global variable
id = System.Diagnostics.Process.Start("C:\Temp\myfile.pdf").Id
Then, when you need to kill the process, just do:
System.Diagnostics.Process.GetProcessById(id).Kill()
(make sure that there is a process with this id that is actually running!)
You may also use the Process.HasExited property to see if the PDF has been closed, and may process your code based on that.
I don't think that it's possible to close a specific PDF file because they are not an independent process, they are sub processes in the task manager.
you can kill the adobe acrobat reader process it self.
Dim AcrobateInstance() As Process = Process.GetProcessesByName("AcroRd32")
If AcrobateInstance.Length > 0 Then
For value As Integer = 0 To AcrobateInstance.Length - 1
BillInstance(value).Kill()
Next
End If
This is in C# but may come in handy...
var myPDFEvent = System.Diagnostics.Process.Start(#"C:\Temp\myfile.pdf");
myPDFEvent.Exited += new EventHandler(myPDFEvent_Exited);
myPDFEvent.EnableRaisingEvents = true;
void myPDFEvent_Exited(object sender, EventArgs e)
{
System.IO.File.Delete(#"C:\Temp\myfile.pdf);
}
This might work:
Process1.Start()
Process1.WaitForExit()
If Process1.HasExited Then
System.IO.File.Delete(Your File Path)
End If
Make sure to add the Process Object onto the form from the toolbox and configure the startinfo section.
If you are having permission problems. Use the AppData folder. It has the necessary permissions that programs need to run
VB.NET level: Beginner
I made a .exe using VB.NET. In this program there are many links to excel files (There are specific folders for excel files).
My problem:
Consider an excel file named as abc.xlsx, which is on my home pc. Link to this file is as follows,
D:\work\data\abc.xlsx
now for obvious reasons, this link will not be valid when I run the .exe on my work pc.
(Later I want to run this .exe on multiple pc's)
How to solve this issue?
My thinking is to create a dynamic link which will update itself based on pc in use or to create a constant link which is independent of pc in use.
Help will be really appreciated.
Thanks in advance
so make the path relative to the .exe
C:\myapp\myapp.exe
c:\myapp\data\abc.xslx
...
So no matter where you app is, you can get to your data like this
Dim dataFolder As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
dataFolder = System.IO.Path.Combine(dataFolder,"data")
Dim theFileIwant as String = System.IO.Path.Combine(datafolder,"abc.xslx")
Try something like this:
Public Function GetDynamicFilename(p_filename As String) As String
Dim tempPath As String
Select Case My.Computer.Name.ToUpper
Case "COMPUTER1"
tempPath = "c:\work\data"
Case "COMPUTER2"
tempPath = "d:\work\files"
End Select
Return String.Format("{0}\{1}", tempPath, p_filename)
End Function
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
Right now i have a line of code, in vb, that calls a text file, like this:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("data5.txt")
data5.txt is a resource in my application, however the application doesn't run because it can't find data5.txt. I'm pretty sure there is another code for finding a .txt file in the resource that i'm overlooking, but i can't seem to figure it out. So does anyone know of a simple fix for this? or maybe another whole new line of code? Thanks in advance!
If you added the file as a resource in the Project + Properties, Resources tab, you'll get its content by using My.Resources:
Dim content As String = My.Resources.data5
Click the arrow on the Add Resource button and select Add Existing File, select your data5.txt file.
I'm assuming that the file is being compiled as an Embedded Resource.
Embedded Resources aren't files in the filesystem; that code will not work.
You need to call Assembly.GetManifestResourceStream, like this:
Dim fileText As String
Dim a As Assembly = GetType(SomeClass).Assembly
Using reader As New StreamReader(a.GetManifestResourceStream("MyNamespace.data5.txt"))
fileText = reader.ReadToEnd()
End Using
First, go to project resources (My Project --> Resources), and drag-and-drop your file, say "myfile.txt", from the file system to the resourses page.
Then:
Imports System.IO
...
Dim stream As New MemoryStream(My.Resources.myfile)
Dim reader As New StreamReader(stream)
Dim s As String = reader.ReadToEnd()