How to Access a txt file in a Folder created inside a VB project - vb.net

I'm creating a VB project for Quiz App (in VS 2013). So I have some preset questions which are inside the project (I have created a folder inside my project and added a text file).
My question is how can I read and write contents to that file? Or if not is there any way to copy that txt file to Documents/MyAppname when installing the app so that I can edit it from that location?

In the example below I am focusing on accessing files one folder under the executable folder, not in another folder else wheres. Files are read if they exists and then depending on the first character on each line upper or lower case the line then save data back to the same file. Of course there are many ways to work with files, this is but one.
The following, created in the project folder in Solution Explorer a folder named Files, add to text files, textfile1.txt and textfile2.txt. Place several non empty lines in each with each line starting with a character. Each textfile, set in properties under solution explorer Copy to Output Directory to "Copy if newer".
Hopefully this is in tune with what you want. It may or may not work as expected via ClickOnce as I don't use ClickOnce to validate this.
In a form, one button with the following code.
Public Class Form1
Private TextFilePath As String =
IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Files")
Private TextFiles As New List(Of String) From
{
"TextFile1.txt",
"TextFile2.txt",
"TextFile3.txt"
}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileName As String = ""
' loop thru each file
For Each fileBaseName As String In TextFiles
FileName = IO.Path.Combine(TextFilePath, fileBaseName)
' only access file if it exist currently
If IO.File.Exists(FileName) Then
' read file into string array
Dim contents As String() = IO.File.ReadAllLines(FileName)
' upper or lower case line based on first char.
' this means you can flip flop on each click on the button
For x As Integer = 0 To contents.Count - 1
If Char.IsUpper(CChar(contents(x))) Then
contents(x) = contents(x).ToLower
Else
contents(x) = contents(x).ToUpper
End If
Next
' save changes, being pesstimistic so we use a try-catch
Try
IO.File.WriteAllLines(FileName, contents)
Catch ex As Exception
Console.WriteLine("Attempted to save {0} failed. Error: {1}",
FileName,
ex.Message)
End Try
Else
Console.WriteLine("Does not exists {0}", FileName)
End If
Next
End Sub
End Class

This may help you
Dim objStreamReader As StreamReader
Dim strLine As String
'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New StreamReader("C:\Boot.ini")
'Read the first line of text.
strLine = objStreamReader.ReadLine
'Continue to read until you reach the end of the file.
Do While Not strLine Is Nothing
'Write the line to the Console window.
Console.WriteLine(strLine)
'Read the next line.
strLine = objStreamReader.ReadLine
Loop
'Close the file.
objStreamReader.Close()
Console.ReadLine()
You can also check this link.

Related

vb.net search directory for files containing *.G(num) but NOT *.GP(num)

I'm fairly familiar with bash, but I'm very, ***very**** new to vb.net. I'm searching for an easy way to find files in a folder that end with .G1, .G2, .G3, etc. but NOT .GP1, .GP2, .GP3, etc. Then for each file I need to copy it to another folder using a different file name but the same extension. I've managed to figure this out for the unique files, but there will be an undefined number of these depending on the project and I need to make sure that I get them all. Hard coding is possible, but very, very ugly. Any suggestions?
Here's the remnants of a failed attempt:
Public Sub FindGFiles()
FileList = IO.Directory.GetFiles(searchDir, ".G[1-99]" + , IO.SearchOption.AllDirectories)
For Each foundfile As String In FileList
If foundfile.Contains(".G#") Then
'copy file somehow and retain file extension
Else
MsgBox("No match")
End If
Next
End Sub
The GetFiles-method does only support * and ? wildcard characters.
So you have to get all files with a *.G*-extension first.
In the For Each-loop one can then use the Like-operator to check the desired pattern:
Public Sub CopyGFiles(searchDir As String, destDir As String)
Dim fileList As String() = IO.Directory.GetFiles(searchDir, "*.G*", IO.SearchOption.AllDirectories)
Dim fileName As String
Dim extension As String
For Each foundfile As String In fileList
fileName = IO.Path.GetFileNameWithoutExtension(foundfile)
extension = IO.Path.GetExtension(foundfile)
If extension Like ".G#" OrElse
extension Like ".G##" Then
'copy file to destination, append "_new" to the filename and retain file extension
IO.File.Copy(foundfile, IO.Path.Combine(destDir, fileName & "_new" & extension))
Else
'pattern not matched
End If
Next
End Sub
The method-call would then be as follows:
CopyGFiles("C:\Temp", "C:\Temp\Dest")
This should be done inside a Try/Catch as different exceptions can occur when working with files.
Try
CopyGFiles("C:\Temp", "C:\Temp\Dest")
Catch ex As Exception
MessageBox.Show("An error occured" + vbCrLf + ex.Message)
End Try

Illegal Characters in path when grabbing text from a file?

I'm getting illegal characters in path, but the directory (the path) will be different for everyone, so I'm not setting a value for the "path", it's what the user chooses in the file explorer.
I haven't seen a solution for VB.net yet so here's the code I have now:
myFileDlog.InitialDirectory = "c:\"
myFileDlog.Filter = "Txt Files (*.txt)|*.txt"
myFileDlog.FilterIndex = 2
myFileDlog.RestoreDirectory = True
If myFileDlog.ShowDialog() =
DialogResult.OK Then
If Dir(myFileDlog.FileName) <> "" Then
Else
MsgBox("File Not Found",
MsgBoxStyle.Critical)
End If
End If
'Adds the file directory to the text box
TextBox1.Text = myFileDlog.FileName
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(myFileDlog.FileName)
Dim lines() As String = IO.File.ReadAllLines(fileReader)
At Dim lines() As String = IO.File.ReadAllLines(fileReader)
It breaks with the Illegal Characters in Path exception, and I'm not sure how to test where the illegal character is, because it's grabbing from your own file directory. Any help with this?
The problem originated from this line:
Dim fileReader As String = My.Computer.FileSystem.ReadAllText(myFileDlog.FileName)
fileReader takes all string contents from the corresponding file name and pass it into File.ReadAllLines method at next line, throwing ArgumentException with illegal file path message if illegal characters found inline.
Correct way to read file contents using ReadAllLines is using predefined file path or directly using FileDialog.FileName property as argument given below:
Using myFileDlog As OpenFileDialog = New OpenFileDialog()
' set dialog filters here
If (myFileDlog.ShowDialog() = DialogResult.OK) Then
If Dir(myFileDlog.FileName) <> "" Then
Dim lines() As String = File.ReadAllLines(myFileDlog.FileName)
For Each line As String In lines
' do something with file contents
Next
Else
' show "file not found" message box
End If
End If
End Using
Since ReadAllLines already being used to fetch all file contents, usage of ReadAllText may be unnecessary there.

new folders from a list, from a text file in vb.net

I want to be able to create new folders from a list that is stored in a text file.
The names are stored like
test1
test2
test3
so my code so far, loads the path to create the new folders, (which is the oldest folder in the given parent folder) stored in another text file "Foldercreation.txt"
then open the file with the names of the folders I want to create, "Folderstocreate.txt" and stores them all in filereader2.
but then when trying to create the folders for each line nothing happens.
My current code;
Dim fileReader, filereader2 As System.IO.StreamReader
Dim stringreader, parfolder As String
Dim path, foldername As List(Of String)
Dim count As Byte
If MsgBox("Are you sure you want to create these folders?,
Before clicking yes, make sure EVERYONE is out of paperport & you have entered the correct numbers.", MsgBoxStyle.YesNo, "WARNING!") = MsgBoxResult.Yes Then
If strnumbx.Text = "" Then
MsgBox("You have not entered a start number for the folders.", MsgBoxStyle.OkOnly, "Error")
End If
'Loads a text file at the given location, to read to.
fileReader = My.Computer.FileSystem.OpenTextFileReader("C:\Data\Test\Foldercreation.txt")
'Set stringreader as the read line from the file
stringreader = fileReader.ReadLine()
path = System.IO.Directory.GetDirectories(stringreader).ToList
path.Sort()
count = path.Count - 1
parfolder = path(count)
'System.IO.Directory.CreateDirectory(parfolder & "\test")
filereader2 = New StreamReader("C:\Data\Test\Folderstocreate.txt", True)
filereader2.ReadToEnd()
For Each line In filereader2.ReadToEnd()
System.IO.Directory.CreateDirectory(parfolder & fileReader.ReadToEnd(count - 1))
count = count + 1
Next
End If
fileReader.Close()
filereader2.Close()
This function would do it but you may want to put in some exception handling.
Directory.CreateDirectory will create all parent folders if they don't exist.
Private Sub CreateAllDirectories(ByVal strFileList As String)
Dim strDirectories As String() = File.ReadAllLines(strFileList)
For Each strDirectory As String In strDirectories
If Not Directory.Exists(strDirectory) Then
Directory.CreateDirectory(strDirectory)
End If
Next
End Sub

Issue using elements in a list in FOR EACH loop

I am new to VB.net and want to write an application to read a text file with a list of paths, count the number of files in all the paths, copy the everything in the path and show the progress via a progress bar with an eta of completion.
So far I have only the text file being read and the counter working correctly, but cannot work out how to use the paths already stored in pathlist list to be the sources in the copy. Here is what I have;
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If System.IO.File.Exists(Application.StartupPath + "\CONFIG.txt") = True Then
Dim pathlist As New List(Of String)
' Open config.txt with the Using statement.
Using r As StreamReader = New StreamReader(Application.StartupPath + "\CONFIG.txt")
' Store contents in this String.
Dim line As String
' Read first line.
line = r.ReadLine
' Loop over each line in file, While list is Not Nothing.
Do While (Not line Is Nothing)
' Add this line to list.
pathlist.Add(line)
'count the files in the directories as we go through the loop
counter = System.IO.Directory.GetFiles(line, "*.*", SearchOption.AllDirectories).Count()
'add # of files to overall count
filecount += counter
' Read the next line.
line = r.ReadLine
Loop
End Using
Else
MessageBox.Show("Config.txt does not exist")
End If
'Label Showing total files
Label1.Text = filecount
End Sub
How would I use the line strings in pathlist to do the following:
Copy the folder with all subfile and directories to the destination folder
Update a counter so I can use a progress bar
Do an time remaining counter, how can this be estimated? Should I be calculating the size in MB's of all the data? Or something similar?
If anyone can assist or link me an example I could use, that would be great!

How to get the file name of a file in VB?

I make a search program for searching a list of files in a computer and then copy the file into a store folder. The file name could be "*11*2.txt" As long as the program find this pattern, it should copy to the store folder. The problem is that I don't know the exactly name of the file before the search and I don't want to rename the file, I don't know how to save the file. Please help
I use the following to find the file, which does its work
Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
Dim To_Path As String
To_Path = Form1.TextBox5.Text
For Each foundFile As String In My.Computer.FileSystem.GetFiles(sDir, FileIO.SearchOption.SearchAllSubDirectories, FileName)
Copy2Local(foundFile, To_Path)
Next
End Sub
Here is the current version of the Copy2Local (Note: it is not working right)
Public Sub Copy2Local(ByVal Copy_From_Path As String, ByVal Copy_To_Path As String)
' Specify the directories you want to manipulate.
Try
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
' Copy the file.
File.Copy(Copy_From_Path, Copy_To_Path)
Catch
End Try
End Sub
First, you should check if ToPath is a valid directory since it's coming from a TextBox:
Dim isValidDir = Directory.Exists(ToPath)
Second, you can use Path.Combine to create a path from separate (sub)directories or file-names:
Dim copyToDir = Path.GetDirectoryName(Copy_To_Path)
Dim file = Path.GetFileName(Copy_From_Path)
Dim newPath = Path.Combine(copyToDir, file)
http://msdn.microsoft.com/en-us/library/system.io.path.aspx
(disclaimer: typed from a mobile)
To answer your question: You can get the file name with Path.GetFileName. Example:
Dim fileName As String = Path.GetFileName(foundFile)
However, there's a bunch of other things wrong with your code:
Here,
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
you are overwriting your source file. This does not seem like a good idea. ;-)
And here,
Try
...
Catch
' Do Nothing
End Try
You are throwing away exceptions that would help you find and diagnose problems. Don't do that. It makes debugging a nightmare.
In vb.net, I'm using the following code to find the filename
Textbox1.Text = New FileInfo(OpenFileDialog.FileName).Name
this code work fine with open file dialog box