Save path to a txt file (VB.net) - vb.net

So, basically I'm doing a "save as" button and when the file is been saved, I want the path from the file that is been saved goes to another txt file tottaly different.
Private Sub saveas_Click(sender As Object, e As EventArgs) Handles Saveas.Click
SaveFileDialog1.InitialDirectory = "C:\Users\marce"
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
SaveFileDialog1.FilterIndex = 2
SaveFileDialog1.ShowDialog()
Dim W As New IO.StreamWriter(SaveFileDialog1.FileName)
W.Write(RichTextBox1.Text)
W.Close()
End Sub

So, your problem is writing to a different file as well? Or somehow, returning two different filenames from the SaveFileDialog? If it's the latter, I don't believe this can be done.
If it's the former, you already know how to write to text files, so this answer seems redundant. Still, the following code (which assumes that the "totally different txt file" is named by appending ".tmp" to the original filename) will save the original path to the second file:
Private Sub saveas_Click(sender As Object, e As EventArgs) Handles Saveas.Click
SaveFileDialog1.InitialDirectory = "C:\Users\marce"
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
SaveFileDialog1.FilterIndex = 2
SaveFileDialog1.ShowDialog()
Dim W As New IO.StreamWriter(SaveFileDialog1.FileName)
W.Write(RichTextBox1.Text)
W.Close()
'new code
'get new filename by appending .tmp to the original filename
Dim tmpFilePath As String = SaveFileDialog1.FileName & ".tmp"
IO.File.WriteAllText(tmpFilePath, SaveFileDialog1.FileName)
End Sub

To add onto #Spyros P's answer is, I would store SaveFileDialog1.ShowDialog() into a variable because if you cancel or X out of the Save window it will still continue onto the saving of the file. Possibly do something like this:
Private Sub saveas_Click(sender As Object, e As EventArgs) Handles Saveas.Click
SaveFileDialog1.InitialDirectory = "C:\Users\marce"
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
SaveFileDialog1.FilterIndex = 2
Dim temp = SaveFileDialog1.ShowDialog()
If temp = False Then Return
Dim W As New IO.StreamWriter(SaveFileDialog1.FileName)
W.Write(RichTextBox1.Text)
W.Close()
'new code
'get new filename by appending .tmp to the original filename
Dim tmpFilePath As String = SaveFileDialog1.FileName & ".tmp"
IO.File.WriteAllText(tmpFilePath, SaveFileDialog1.FileName)
End Sub
Over all #Spyros P. is correct, all I changed was I added the variable for the SaveFileDialog1.ShowDialog

Related

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

Import CSV file to database using VB

I need to import the information from a CSV txt file to a database using the DataGridView in my form. The application should allow the user to open a .txt file and then update the DataGridView table in my form. I am able to get the file, but am unable to update the grid using the file. I can update textboxes, but cannot figure out how to update the grid. Can anyone help me out with this?
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Public Class Form1
Private fileToOpen As String 'the file to be opened and read
Private responseFileDialog As DialogResult 'response from OpenFileDialog
Private myStreamReader As StreamReader 'the reader object to get contents of file
Private myStreamWriter As StreamWriter 'the writer object to save contents of textbox
Private myTextFieldParser As TextFieldParser ' To parse text to searched.
Dim myDataAdapter As OleDb.OleDbDataAdapter
Dim myString() As String
Dim myRow As DataRow
Private Sub PeopleBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles PeopleBindingNavigatorSaveItem.Click
Me.Validate()
Me.PeopleBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.MyContactsDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyContactsDataSet.People' table. You can move, or remove it, as needed.
Me.PeopleTableAdapter.Fill(Me.MyContactsDataSet.People)
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim fileContentString As String 'contents of the file
Dim update As New OleDb.OleDbCommandBuilder(myDataAdapter)
'Dim myRow As DataRow
'set the properties of the OpenFileDialog object
OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.CurrentDirectory
OpenFileDialog1.Title = "Select File to View..."
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
'responseFileDialog contains holds the response of the user (which button they selected)
responseFileDialog = OpenFileDialog1.ShowDialog()
'check to see if the user select OKAY, if not they selected CANCEL so don't open anything
If (responseFileDialog <> System.Windows.Forms.DialogResult.Cancel) Then
'make sure there isn't a file already open, if there is then close it
If (myStreamReader IsNot Nothing) Then
myStreamReader.Close()
'TextBoxFileOutput.Clear()
End If
'open the file and read its text and display in the textbox
fileToOpen = OpenFileDialog1.FileName
myStreamReader = New StreamReader(OpenFileDialog1.FileName)
initTextFieldParser()
'loop through the file reading its text and adding it to the textbox on the form
Do Until myStreamReader.Peek = -1
fileContentString = myStreamReader.ReadLine()
'Try
' myTextFieldParser = New TextFieldParser(fileToOpen)
' myTextFieldParser.TextFieldType = FieldType.Delimited
' myTextFieldParser.SetDelimiters(",")
'Catch ex As Exception
' MessageBox.Show("Cannot Open File to Be Read!")
'End Try
myTextFieldParser.TextFieldType = FieldType.Delimited
myString = TextFieldParser.NewLine()
myRow.Item("FirstName") = myString(1)
MyContactsDataSet.Tables("People").Rows.Add(myRow)
PeopleTableAdapter.Update(MyContactsDataSet)
'TextBoxFileOutput.AppendText(fileContentString)
'TextBoxFileOutput.AppendText(Environment.NewLine)
Loop
'close the StreamReader now that we are done with it
myStreamReader.Close()
'SaveToolStripMenuItem.Enabled = True
End If
End Sub
Private Sub initTextFieldParser()
'Close myTextFieldParser in case the user is surfing through the records and then
'decides to search for a particular last name --> Basically start searching from beginning of the file
If (myTextFieldParser IsNot Nothing) Then
myTextFieldParser.Close()
End If
Try
myTextFieldParser = New TextFieldParser(fileToOpen)
myTextFieldParser.TextFieldType = FieldType.Delimited
myTextFieldParser.SetDelimiters(",")
Catch ex As Exception
MessageBox.Show("Cannot Open File to Be Read!")
End Try
End Sub
End Class
updating gridview with your file content
Import System.IO as we gonna need StreamReader
Using reader As New StreamReader("filepath")
DataGridView1.Columns.Add("col1",reader.ReadToEnd())
End Using
check this out!

CopyFile isn't copying my file with the same extension?

I am trying to make it so my user can copy files from one folder to another folder, their playlist folder, so that they can use it throughout my program. So I tried this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim result As DialogResult = MessageBox.Show("Are you sure you want to finish the playlist?", "Finish Playlist- WikiFinder", MessageBoxButtons.YesNo)
If (result = DialogResult.Yes) Then
For Each Item In ListBox1.Items
Dim str As String = IO.Path.Combine(MusicMenu.FolderBrowserDialog2.SelectedPath, "DONUTS")
My.Computer.FileSystem.CopyFile(Item.ToString(), str)
Next
Else
End If
End Sub
This works and makes the file, but the issue is I told it to copy an MP3 file and it just gave me a "File". Is there any way I can copy the file AND keep the original file's extension?
Since you pass only the directory to the CopyFile function, it creates a FILE.
Pass filename with Extension.
For Each Item In ListBox1.Items
Dim str As String = IO.Path.Combine(MusicMenu.FolderBrowserDialog2.SelectedPath, "DONUTS")
str = IO.Path.Combine(str,IO.Path.GetFileName(Item.ToString()))
My.Computer.FileSystem.CopyFile(Item.ToString(), str)
Next
Now the files will be copied to your DONUTS folder.

Directory.GetFiles - SearchOption.AllDirectories Does not give files in subfolders (vb)

Directory.GetFiles - SearchOption.AllDirectories Does not give files that are located in subfolders. I'm trying to copy al .jpg files from a usb to the computer but when files are located in sub-folders, it does not copy them.
Private Sub ButtonStart_Click(sender As Object, e As EventArgs) Handles ButtonStart.Click
Dim sourceDir As String = ComboBoxUsbSelect.Text
Dim backupDir As String = FileDestination
Try
Dim picList As String() = Directory.GetFiles(sourceDir, "*.jpg", SearchOption.AllDirectories)
' Copy picture files.
For Each f As String In picList
'Remove path from the file name.
Dim fName As String = f.Substring(sourceDir.Length)
' Use the Path.Combine method to safely append the file name to the path.
' Will overwrite if the destination file already exists.
If delete = False Then
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), True)
Else
File.Move(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName))
End If
Next
Catch dirNotFound As DirectoryNotFoundException
Console.WriteLine(dirNotFound.Message)
End Try
MessageBox.Show("Done!")
End Sub

Rename directory using save filedialog filename

I Have a folder in this path
C:\Users\XXX\Desktop\Original\XXX\bin\Debug\Backup
And when I save my project with "XXX" name the same time I need to change the Backup Folder using that save filedialog name and it shouldn't overwrite it.
Can anyone suggest me how to do this:
Here is the code how I am doing it and it didn't work for me:
Private Sub SaveProject_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveProject.Click
Using sfdlg As New Windows.Forms.SaveFileDialog
sfdlg.OverwritePrompt = True
sfdlg.InitialDirectory = "C:\"
sfdlg.FileName = "Untitled"
sfdlg.DefaultExt = "amk"
sfdlg.Filter = "AquaMark Project|*.amk"
If sfdlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim SaveData As New gCanvasData
With SaveData
frmDisplay.GCanvas1.UnselectCurrentAnotate()
.gAnnotates = frmDisplay.GCanvas1.gAnnotates
.Image = frmDisplay.GCanvas1.Image
End With
Using objStreamWriter As New StreamWriter(sfdlg.FileName)
Dim x As New XmlSerializer(GetType(gCanvasData))
x.Serialize(objStreamWriter, SaveData)
objStreamWriter.Close()
End Using
End If
sfdlg.Dispose()
System.IO.Path.GetFileNameWithoutExtension(sfdlg.FileName)
IO.Directory.Move(Application.StartupPath + "\Backup\", Application.StartupPath + "\Backup\" & System.IO.Path.GetFileNameWithoutExtension(sfdlg.FileName))
End Using
End Sub
But can anyone clearly mention me how to do it?
Based on the error, you most likely won't be able to save the file and change the backup folder name through the same SaveFileDialog.
Break it into two steps:
Save the file through the SaveFileDialog. Be sure to capture the filename from SaveFileDialog so you can use it in step 2, as it may be out of scope after you close the SaveFileDialog window.
Rename the backup folder using the command above, but after you've closed the SaveFileDialog so the handle is released.
EDIT
As I noted in step 1, you need to save the filename somewhere so you can use it in step 2.
Private Sub SaveProject_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveProject.Click
' Set up a variable to hold the filenam
Dim fileName As String
Using sfdlg As New Windows.Forms.SaveFileDialog
sfdlg.OverwritePrompt = True
sfdlg.InitialDirectory = "C:\"
sfdlg.FileName = "Untitled"
sfdlg.DefaultExt = "amk"
sfdlg.Filter = "AquaMark Project|*.amk"
If sfdlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim SaveData As New gCanvasData
' Store the filename from the SaveFileDialog
fileName = sfdlg.FileName
With SaveData
frmDisplay.GCanvas1.UnselectCurrentAnotate()
.gAnnotates = frmDisplay.GCanvas1.gAnnotates
.Image = frmDisplay.GCanvas1.Image
End With
Using objStreamWriter As New StreamWriter(sfdlg.FileName)
Dim x As New XmlSerializer(GetType(gCanvasData))
x.Serialize(objStreamWriter, SaveData)
objStreamWriter.Close()
End Using
End If
'Calling Dispose is redundant since sfdlg was in a Using block
'sfdlg.Dispose()
' You can't use sfdlg.FileName here as the object is out of scope
'System.IO.Path.GetFileNameWithoutExtension(sfdlg.FileName)
'IO.Directory.Move(Application.StartupPath + "\Backup\", Application.StartupPath + "\Backup\" & System.IO.Path.GetFileNameWithoutExtension(sfdlg.FileName))
' Use the value in fileName from above
System.IO.Directory.Move(Application.StartupPath + "\Backup\", Application.StartupPath + "\Backup\" & System.IO.Path.GetFileNameWithoutExtension(fileName))
End Using
End Sub