Moving files into new folder using VB - vb.net

I have one Log file that keep a full path for *.docx extension every time it's created. The problem is I don't know how to split the file's name from the full path. Before move it, I can select which Path that have been created using CheckedListBox and move it to target folder.
For example in my Log File I store (file has been created: C:\Users\AsrahLim\Desktop\New Microsoft Word Document.docx), all I need is the file's name "New Microsoft Word Document.docx" and move it to new folder .
This is my target folder: C:\Users\AsrahLim\Google Drive. Below is my code.
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.Items.Add("Select/UnSelect All")
CheckedListBox1.CheckOnClick = True
Dim FILE_NAME As String = "C:\Users\AsrahLim\Desktop\LogFile.txt"
If System.IO.File.Exists(FILE_NAME) Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
CheckedListBox1.Items.Add(objReader.ReadLine())
btnSave.Enabled = True
Loop
Else
MessageBox.Show("File Does Not Exist")
Close()
End If
End Sub
Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs) Handles btnSave.Click
If CheckedListBox1.CheckedItems.Count <> 0 Then
For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Dim SourcePath As String = CheckedListBox1.SelectedItem
Dim MoveLocation As String = "C:\Users\AsrahLim\Google Drive"
SourcePath = SourcePath.Substring(SourcePath.LastIndexOf("- ") + 1)
If File.Exists(SourcePath) = True Then
File.Move(SourcePath, MoveLocation)
MsgBox("File Moved")
Else
MsgBox("File Not move")
End If
Next
End If
End Sub
Private Sub btnCancel_Click(sender As System.Object, e As System.EventArgs) Handles btnCancel.Click
Close()
End Sub
End Class

Don't try to implement your own logic for path manipulations. Use the shared Path class in System.IO instead.
Dim filename As String = Path.GetFileName(SourcePath)
Then you can construct the new path name with
Dim destinationPath As String = Path.Combine(MoveLocation, filename)
Also, test if the file exists in the destination location as well and delete it if it exists.
If File.Exists(SourcePath) Then
Dim filename As String = Path.GetFileName(SourcePath)
Dim destinationPath As String = Path.Combine(MoveLocation, filename)
If File.Exists(destinationPath) Then
File.Delete(destinationPath)
End If
File.Move(SourcePath, destinationPath)
MsgBox("File Moved")
Else
MsgBox("File Not move")
End If
A side note: I don't like statements like If File.Exists(SourcePath) = True Then. Often people think that an If-statement requires a comparison. This is not true. All it needs is a Boolean expression, i.e. an expression returning either True or False. File.Exists(SourcePath) is an expression which does exactly this. The additional = True doesn't change anything and is superfluous, because if File.Exists(SourcePath) returns True then True = True is True and if File.Exists(SourcePath) returns False then False = True is False. = True is a neutral operation as is * 1 for numbers. You don't say Foo(1 * x), you just say Foo(x).

Very simple in your log you could store with a delimiter for instance:
New File Created*C:\test.docx
The star symbol is a banned character in file name so you can be sure it wont be in the path. After this you can just do
Dim data() As String
data = Split(File.ReadAllText(LogFile.txt), StringSplitOptions.RemoveEmptyEntries)
File.Move(data(1), Path.Combine(MoveLocation , Path.GetFileName(data(1)))
Ideally you just shouldn't store files a bit everywhere on your computer and use distinct folders.

Related

Importing data from text file in VB.NET

So, I am trying to develop a book database. I have created a table with 11 columns which populates a DGV, where only 6 columns are showed. The full data of each book is shown in a lower part of the form, where I have textboxes, which are bounded (BindingSource) to the table, that change as I move in the DGV.
Now, what I want to do is to have the posibility to export/import data from a file.
I have accomplished the exporting part with the following code:
Private Sub BtnExport_Click(sender As Object, e As EventArgs) Handles BtnExport.Click
Dim txt As String = String.Empty
For Each row As DataGridViewRow In DbdocsDataGridView.Rows
For Each cell As DataGridViewCell In row.Cells
'Add the Data rows.
txt += CStr(cell.Value & ","c)
Next
'Add new line.
txt += vbCr & vbLf
Next
Dim folderPath As String = "C:\CSV\"
File.WriteAllText(folderPath & "DataGridViewExport.txt", txt)
End Sub
However, I can't manage to import from the txt. What I've tried is this: https://1bestcsharp.blogspot.com/2018/04/vb.net-import-txt-file-text-to-datagridview.html
It works perfectly if you code the table and it populates de DGV without problem. I can't see how should I adapt that code to my need.
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
DbdocsDataGridView.DataSource = table
Dim filas() As String
Dim valores() As String
filas = File.ReadAllLines("C:\CSV\DataGridViewExport.txt")
For i As Integer = 0 To filas.Length - 1 Step +1
valores = filas(i).ToString().Split(",")
Dim row(valores.Length - 1) As String
For j As Integer = 0 To valores.Length - 1 Step +1
row(j) = valores(j).Trim()
Next j
table.Rows.Add(row)
Next i
End Sub
That is what I've tried so far, but I always have an exception arising.
Thanks in advance to anyone who can give me an insight about this.
The DataTable class has built-in methods to load/save data from/to XML called ReadXml and WriteXml. Take a look at example which uses the overload to preserve the schema:
Private ReadOnly dataGridViewExportPath As String = IO.Path.Combine("C:\", "CSV", "DataGridViewExport.txt")
Private Sub BtnExport_Click(sender As Object, e As EventArgs) Handles BtnExport.Click
table.WriteXml(path, XmlWriteMode.WriteSchema)
End Sub
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
table.ReadXml(path)
End Sub
While users can manually edit the XML file that is generated from WriteXML, I would certainly not suggest it.
This is code which writes to a text file:
speichern means to save.
Note that I use a # in my example for formatting reasons. When reading in again, you can find the # and then you know that and that line is coming...
And I used Private ReadOnly Deu As New System.Globalization.CultureInfo("de-DE") to format the Date into German format, but you can decide yourself if you want that. 🙂
Note that I'm using a FileDialog that I downloaded from Visual Studio's own NuGet package manager.
Private Sub Button_speichern_Click(sender As Object, e As EventArgs) Handles Button_speichern.Click
speichern()
End Sub
Private Sub speichern()
'-------------------------------------------------------------------------------------------------------------
' User can choose where to save the text file and the program will save it .
'-------------------------------------------------------------------------------------------------------------
Dim Path As String
Using SFD1 As New CommonSaveFileDialog
SFD1.Title = "store data in a text file"
SFD1.Filters.Add(New CommonFileDialogFilter("Textdatei", ".txt"))
SFD1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If SFD1.ShowDialog() = CommonFileDialogResult.Ok Then
Path = SFD1.FileName & ".txt"
Else
Return
End If
End Using
Using textfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, True, System.Text.Encoding.UTF8)
textfile.WriteLine("Timestamp of this file [dd.mm.yyyy hh:mm:ss]: " & Date.Now.ToString("G", Deu) & NewLine & NewLine) 'supposed to be line break + 2 blank lines :-)
textfile.WriteLine("your text")
textfile.WriteLine("#") 'Marker
textfile.Close()
End Using
End Sub
Private Sub FormMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
speichern()
End Sub
And this is to read from a text file:
'read all Text
Dim RAT() As String = System.IO.File.ReadAllLines(Pfad, System.Text.Encoding.UTF8)
If RAT.Length = 0 Then Return Nothing
For i As Integer = 0 To RAT.Length - 1 Step 1
If RAT(i) = "#" OrElse RAT(i) = "" Then Continue For
'do your work here with (RAT(i))
Next

Limited Multiselect in open file dialog?

I want the user to have the option to select multiple files through openfiledialog which I have in my code, but then if the user selects a file from one folder he is then restricted to select another file only from this specific folder. What is the best way to approach to this problem?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim openfiledialog1 As New OpenFileDialog
With openfiledialog1
.Title = "Select your models"
.Filter = "Solidworks Files|*.sldprt;"
.Multiselect = True
End With
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
For Each mfile As String In openfiledialog1.FileNames
'' Add all filenames in a txt file, in a column
Next
End If
End Sub
As far as I know, OpenFileDialog doesn't offer a way to prevent the user from navigating to another directory.
One approach would be to create a class-level variable that holds the value of the recently used directory path. Then, whenever a new file is selected, you check its directory path against the one previously stored. If it matches, continue. If not, break the operation and report to the user.
Here's a complete example:
Private openFileDialog1 As New OpenFileDialog
Private modelsDirectory As String = Nothing
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With openFileDialog1
.Title = "Select your models"
.Filter = "Solidworks Files|*.sldprt;"
.Multiselect = True
.FileName = Nothing
' Open the dialog and navigate to the previous direcoty by default.
.InitialDirectory = modelsDirectory
End With
If openFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub
Dim dirPath As String = IO.Path.GetDirectoryName(openFileDialog1.FileName)
If modelsDirectory IsNot Nothing AndAlso
Not dirPath.Equals(modelsDirectory, StringComparison.OrdinalIgnoreCase) Then
MessageBox.Show("Models must be selected from the following directory:" &
vbNewLine & modelsDirectory, "Restricted Directory")
Exit Sub
End If
' Store the value of the current directory path.
modelsDirectory = dirPath
For Each filePath As String In openFileDialog1.FileNames
' TODO: use the selected files as you see fit.
Next
End Sub
You might want to remove this restriction at some point (e.g., if you clear the list of selected files). You can achieve that by simply setting modelsDirectory to Nothing:
Private Sub ClearFilesList
' TODO: clear the files.
modelsDirectory = Nothing
End Sub

Does not enable a menustrip item when the folder has files with

My form's Load event handler checks if a folder is available (if not, it creates it) and if available checks if there are files with a specific extension. If there's at least one file with that extension, it will enable an option on a MenuStrip (referred to as QuickLoadMenuStripItem).
The problem is when it checks a folder when it's on the user's folder, it does not work, regardless if there is or not. It executes the code normally, but it always gives false. Here's the code:
Public Class BaseForm1
Private Sub BaseForm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ImportFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\Immortal Sins\Saves\"
If (Not Directory.Exists(ImportFolder)) Then
Directory.CreateDirectory(ImportFolder)
QuickStartToolStripMenuItem.Enabled = False
Else
Directory.GetFiles(ImportFolder)
For Each tempstring As String In ImportFolder
If tempstring.Contains(".isgsf") Then
QuickStartToolStripMenuItem.Enabled = True
Else
QuickStartToolStripMenuItem.Enabled = False
End If
Next
End If
End Sub
End Class
For reference, it checks on C:\Users\\Immortal Sins\Saves. The files have the .isgsf extension.
You could just do:
Private Sub BaseForm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ImportFolder As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Immortal Sins\Saves\")
If (Not Directory.Exists(ImportFolder)) Then
Directory.CreateDirectory(ImportFolder)
QuickStartToolStripMenuItem.Enabled = False
Else
QuickStartToolStripMenuItem.Enabled = (Directory.GetFiles(ImportFolder, "*.isgsf").Length > 0)
End If
End Sub
You're not storing the file list on ImportFolder when retrieving the content at Directory.GetFiles(ImportFolder)
Also, you're not checking the file extension. You're checking if the file contains a certain string.
Try this instead
Dim ImportFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\Immortal Sins\Saves\"
If (Not Directory.Exists(ImportFolder)) Then
Directory.CreateDirectory(ImportFolder)
QuickStartToolStripMenuItem.Enabled = False
Else
Dim fileEntries As String() = Directory.GetFiles(ImportFolder)
For Each file As String In fileEntries
Dim extension As String = System.IO.Path.GetExtension(file)
If extension = "isgsf" Then
QuickStartToolStripMenuItem.Enabled = True
Exit For 'Once a .isgsf is found the next files should't be checked
Else
QuickStartToolStripMenuItem.Enabled = False
End If
Next
End If

Folder name to combobox in VB.NET

I wanted my combo box to fill in runtime by checking all directory name in a directory.
Here is my code :
Private Sub EDITFORM_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call CLEAR()
End Sub
Private Sub CLEAR()
qtytb.Enabled = False
parttb.Clear()
qtytb.Clear()
DTCB.Items.Clear()
MTHCB.SelectedIndex = ""
YRCB.SelectedIndex = ""
RadioButton2.Checked = True
RadioButton1.Checked = True
TextBox1.Clear()
TextBox2.Clear()
>> Dim di As New DirectoryInfo("D:\DATABASE\" & Pick_Item.deptlbl.Text)
If di.Exists = True Then
For Each subDirectory As DirectoryInfo In di.GetDirectories()
YRCB.Items.Add(CInt(subDirectory.Name.ToString))
Next
End If<<
End Sub
That is my complete code to the combobox and load form
But when i debug, it just appear a messagebox with error so i dont know where exactly is my error in the code
"Conversion from "" string to integer is not valid"
Some thing like this. So, how can i add the folder name to my combobox? Exactly my Directories name are using Integer (Cause name it by year), if i add Directories by name(Not integer) it can. Any help would be appreciated
Your problem is in the TOP line
Dim folders() As String = IO.Directory.GetDirectories("D:\DATABASE\")
For Each folder As String In folders
Combobox1.Items.Add(folder)
Next
Update
Is there any other code which is present in the subroutine/event but is not included above? I tried it and it works fine even if the folder names are numbers
I think the problem is in these lines
MTHCB.SelectedIndex = ""
YRCB.SelectedIndex = ""
change them to
MTHCB.SelectedIndex = -1
YRCB.SelectedIndex = -1

How I can know if there is at least one type of file in a directory?

For example: I want to know if there are images in a directory (eg. ".jpg") I want to return a boolean value that confirm whether there are files with that extension or not.
At first I started with the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Path1 As String
FolderBrowserDialog1.ShowDialog()
Path1 = FolderBrowserDialog1.SelectedPath
TextBox1.Text = FolderBrowserDialog1.SelectedPath 'ignore this
If System.IO.File.Exists(Path1 + "\*.jpg") = True Then
Label1.Text = "At least there is a .jpg"
End If
End Sub
It did not work and I thought use System.IO.Directory.GetFiles.The problem is how I can use it to give me back a value true / false, or rather to see if there is such file types
You can use Directory.EnumerateFiles along with Enumerable.Any:
Dim exists As Boolean = Directory.EnumerateFiles(folderName, "*.jpg").Any()
GetFiles should also work (if you're in .NET 3.5), but will be less efficient:
Dim exists As Boolean = Directory.GetFiles(folderName, "*.jpg").Any()
Private Function FileExists(folderPath As String, extension As String) As Boolean
Return (Directory.GetFiles(folderPath, "*." + extension).Length <> 0)
End Function