how to save file in desired path with StreamWriter - vb.net

I am saving a .csv file in my directory by giving the path with StreamWriter. Now i want to give the option to user to save that file desired path. how can it. help me somebody.
Dim objStreamWriter = New IO.StreamWriter("c:\FaultTypesByMonth.csv")
Dim Str As String
Dim i As Integer
Dim j As Integer
Dim headertext1(rsTerms.Columns.Count) As String
Dim k As Integer = 0
Dim arrcols As String = Nothing
For Each column As DataColumn In TempTab.Columns
headertext1(k) = column.ColumnName
arrcols += column.ColumnName.ToString() + ","c
k += 1
Next
objStreamWriter.WriteLine(arrcols)
For i = 0 To (TempTab.Rows.Count - 1)
For j = 0 To (TempTab.Columns.Count - 1)
'this IF statement stops it from adding a comma after the last field
If j = (TempTab.Columns.Count - 1) Then
Str = (TempTab.Rows(i)(j).ToString)
Else
Str = (TempTab.Rows(i)(j).ToString & ",")
End If
objStreamWriter.Write(Str)
Next
objStreamWriter.WriteLine()
Next
objStreamWriter.Close()
' After save the file in C:/ I want to save the same file in any other Path for my convenience.
'------------------------------------------------------------------------------------------------
Dim sd As New SaveFileDialog
sd.Filter = "CSV Files (*.csv)|*.csv"
sd.FileName = "FaultTypesByMonth"
If sd.ShowDialog = Windows.Forms.DialogResult.OK Then
'save the file here
Debug.WriteLine("Save file location:" + sd.FileName)
End If

If it's a console application you could read a path argument from the command line.
If it's a GUI application you can show a save file dialog box, in WinForms use the SaveFileDialog class.
To save a file to different locations put the writer code in a function which takes the file path as an argument:
Sub SaveFile(filePath As String)
Dim objStreamWriter = New IO.StreamWriter(filePath)
' ... your code here
End Sub
Sub ButtonClick
SaveFile("c:\FaultTypesByMonth.csv")
' ... SaveFileDialog code
SaveFile(sd.Filename)
End Sub
To copy a file use File.Copy:
' ... SaveFileDialog code
File.Copy("c:\FaultTypesByMonth.csv", sd.Filename)

Use the SaveFileDialog class
Simple example:
Private Sub SaveFile()
Dim sd As New SaveFileDialog
sd.Filter = "CSV Files (*.csv)|*.csv"
If sd.ShowDialog = Windows.Forms.DialogResult.OK Then
'save the file here
Debug.WriteLine("Save file location:" + sd.FileName)
End If
End Sub

Related

Renaming files listed within a listbox

I'm trying to create a little program thats able to alter the names of shotcuts, from a listbox-index.
I've created a button wich list every file with the targeted "extension"(targeted with combobox1), from where I want another button to be able to alter the files names:
Button 1 code(Searching for the files):
Dim kilde As New FolderBrowserDialog
If kilde.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim mappe = New System.IO.DirectoryInfo(kilde.SelectedPath)
txtbSti.Text = kilde.SelectedPath
End If
For Each f In Directory.GetFiles(txtbSti.Text, "*" & ComboBox1.Text & "*", SearchOption.AllDirectories)
If File.Exists(f) Then
With ListBox1
With .Items
.Add(f)
End With
End With
End If
Next f
This gives me a list with the desired files.
Is there a way, to rename the files, in my case,listed within listbox1, line by line?
Button 2 (not functioning)
For Each r As String In ListBox1.Items
System.IO.Path.ChangeExtension(ComboBox1.Text, " ")
Next r
You can use File.Move to "rename" a file:
System.IO.File.Move("oldfilename", "newfilename")
For example:
For Each oldFilePath As String In ListBox1.Items
If System.IO.File.Exists(oldFilePath) Then
Dim dir = System.IO.Path.GetDirectoryName(oldFilePath)
Dim newFilePath = System.IO.Path.Combine( dir, "newFileName")
System.IO.File.Move(oldFilePath, newFilePath)
End If
Next
Edit: In this case, remove the automatic generated extension ".avi - Shortcut"
If you just want to change an extension you can use Path.ChangeExtension:
System.IO.Path.ChangeExtension(oldFilePath, "new_extension")
Update: oh, sorry, it's a part of the name; the file is named, example; J:\Homemovies\Jumping around.avi - Shortcut.lnk, I want to remove the ".avi - Shortcut" part of the name on the actual file(s) listed within the listbox1 that is set up to find all the files within a targeted folder with that particular extension within it's name; J:\Homemovies\Jumping around.lnk
You can use String.Replace:
Dim name = System.IO.Path.GetFileName(oldFilePath).ToLowerInvariant()
Dim newName = name.Replace(".avi - shortcut.", ".")
Dim newPath = System.IO.Path.Combine(
System.IO.Path.GetDirectoryName(oldFilePath), newName)
Update2: still can't get either of those solutions to work
Here is a complete working sample:
First, read the shortcuts from your directory:
Dim dir = "C:\Temp\Homemovies"
For Each fn In Directory.EnumerateFileSystemEntries(dir, "*avi - shortcut*.*", SearchOption.AllDirectories)
ListBox1.Items.Add(fn)
Next
Second (in your button-click handler), rename those .Ink files by removing the part that contains(substring)"avi - shortcut", also handling the case that it already exists:
For Each fn As String In ListBox1.Items
If File.Exists(fn) Then
Dim folder = Path.GetDirectoryName(fn)
Dim fileName = Path.GetFileNameWithoutExtension(fn)
Dim extension = Path.GetExtension(fn)
Dim dotParts = fileName.Split("."c)
Dim allButAviShortCut = From part In dotParts
Where part.IndexOf("avi - shortcut", StringComparison.InvariantCultureIgnoreCase) = -1
Dim newFileName = String.Join(".", allButAviShortCut)
Dim newPath = System.IO.Path.Combine(dir, newFileName & extension)
Dim number = 0
While File.Exists(newPath)
' exists already, append number
number += 1
Dim newFileNameWithNum = String.Format("{0}_{1}", newFileName, number)
newPath = System.IO.Path.Combine(dir, newFileNameWithNum & extension)
End While
System.IO.File.Move(fn, newPath)
End If
Next
Consider the following:
ListBox1 contains list of all files in the selected directory.
txtbSti is the text box which holds the path to the selected directory.
Each file is renamed as New_fileX where X is the index of the file in the ListBox1
Now take a look into the code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer = 0
For Each r As String In ListBox1.Items
i += 1
My.Computer.FileSystem.RenameFile(txtbSti.Text & ":\" & r, "New_file" & i & ".txt")
Next r
End Sub

vb.net showdialog openfile to string

i'm trying to importe a csv file after creating on the same application, the only probleme is that even if a string matchs a line from the file, comparing them on vb.net dosn't give a true boolean i know i didn't make any mistakes because of the line with the commentary 'THIS LINE , i use a pretty small list to do my test and in that loop, there is always one element that matches exactly the string, but comparing them on vb.net dosn't return a true. the result of this is that just after saving the file to my computer while still having it on my listview1 on the application, i load it to the application again and it duplicates everything
Dim open As New OpenFileDialog
open.Filter = "CSV Files (*.csv*)|*.csv"
If open.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim File As String = My.Computer.FileSystem.ReadAllText(open.FileName)
Dim lines() As String = File.Split(Environment.NewLine)
For i = 1 To (lines.Count - 1)
Dim line As String = lines(i)
Dim Columns() As String = line.Split(";")
Dim addLin As New ListViewItem(Columns)
Dim Alr As Boolean = False
Dim st as string=listView1.Items.Item(k).SubItems.Item(0).Text
For k = 0 To (ListView1.Items.Count - 1)
Dim st as string=listView1.Items.Item(k).SubItems.Item(0).Text
MsgBox(Columns(0)& Environment.NewLine & st) 'THIS LINE
If ListView1.Items.Item(k).SubItems.Item(0).Text = Columns(0) Then
Alr = True
MsgBox("true") 'never showsup even when the previous one show the match
End If
next
If Alr = False Then
MsgBox("false") 'the msgbox is only to check
ListView1.Items.Add(addLin)
End If
next
end if

Generate multiple files in a loop using visual basic

I am new to Visual Basic.
I wonder if I wanna generate multiple files in a while loop. It seems that the FILESTREAM cannot be reused even I set it into nothing at the end of loop.
Dim fs as FILESTREAM = nothing
Dim i as integer = 0
Dim path as string = "c:\users\...\Desktop\"
Dim name as string = nothing
while i<10
name = path + i.tostring
fs=File.Create(name)
i+=1
fs=nothing
end while
Thank you very much!
It's not clear if you're using the FileStream just to create a blank file or if you're planning on performing other operations against the new files. If you're just trying to create empty files and manipulate them later, after creation, then this should work:
Sub Main()
Dim i As Integer = 0
' You can use properties of My.Computer to find the current user's Desktop
Dim path As String = My.Computer.FileSystem.SpecialDirectories.Desktop
Dim fileName As String = String.Empty
While i < 10
fileName = path & "\" & i.ToString
System.IO.File.Create(fileName)
i += 1
End While
End Sub

Unhide all hidden files, folders, subfolders and subfiles except access denied path using Visual Basic

My code below albe to Unhide all hidden files, folders, subfolders and subfiles. The problem is it'll stop if any access denied path. How to make the code skip access denied path and continue with other paths.
Dim MyDrive As String = "D:\"
Dim FileCounter As Integer = 0
Dim FolderCounter As Integer = 0
Dim DriveObj As New IO.DirectoryInfo(MyDrive)
Dim Files As IO.FileInfo() = DriveObj.GetFiles("*.*", IO.SearchOption.AllDirectories)
Dim Directories As IO.DirectoryInfo() = DriveObj.GetDirectories("*.*", IO.SearchOption.AllDirectories)
Dim Filename As IO.FileSystemInfo
For Each Filename In Files
On Error Resume Next
If (IO.File.GetAttributes(Filename.FullName) And IO.FileAttributes.Hidden) = IO.FileAttributes.Hidden Then
' Show the file.
IO.File.SetAttributes(Filename.FullName, IO.FileAttributes.Normal)
FileCounter = FileCounter + 1
End If
Next
Dim DirectoryName As IO.DirectoryInfo
For Each DirectoryName In Directories
On Error Resume Next
If (IO.File.GetAttributes(DirectoryName.FullName) And IO.FileAttributes.Hidden) = IO.FileAttributes.Hidden Then
' Show the folder.
IO.File.SetAttributes(DirectoryName.FullName, IO.FileAttributes.Normal)
FolderCounter = FolderCounter + 1
End If
Next
When I was testing code, I realised that DriveObj.GetFiles(...) and DriveObj.GetDirectories(...) are stopping when access is denied, not For loops. To fix that, you have to use recursive file and directory listing.
Private Function GetFilesRecursive(ByVal initial As String) As List(Of String)
' This list stores the results.
Dim result As New List(Of String)
' This stack stores the directories to process.
Dim stack As New Stack(Of String)
' Add the initial directory
stack.Push(initial)
' Continue processing for each stacked directory
Do While (stack.Count > 0)
' Get top directory string
Dim dir As String = stack.Pop
Try
' Add all immediate file paths
result.AddRange(Directory.GetFiles(dir, "*.*"))
' Loop through all subdirectories and add them to the stack.
Dim directoryName As String
For Each directoryName In Directory.GetDirectories(dir)
stack.Push(directoryName)
Next
Catch ex As Exception
End Try
Loop
' Return the list
Return result
End Function
Private Function GetDirectoriesRecursive(ByVal initial As String) As List(Of String)
' This list stores the results.
Dim result As New List(Of String)
' This stack stores the directories to process.
Dim stack As New Stack(Of String)
' Add the initial directory
stack.Push(initial)
' Continue processing for each stacked directory
Do While (stack.Count > 0)
' Get top directory string
Dim dir As String = stack.Pop
Try
' Add all immediate file paths
result.AddRange(Directory.GetDirectories(dir, "*.*"))
' Loop through all subdirectories and add them to the stack.
Dim directoryName As String
For Each directoryName In Directory.GetDirectories(dir)
stack.Push(directoryName)
Next
Catch ex As Exception
End Try
Loop
' Return the list
Return result
End Function
Private Sub Unhide()
Dim MyDrive As String = "D:\"
Dim FileCounter As Integer = 0
Dim FolderCounter As Integer = 0
Dim Files As List(Of String) = GetFilesRecursive(MyDrive)
Dim Directories As List(Of String) = GetDirectoriesRecursive(MyDrive)
For Each Filename In Files
If (IO.File.GetAttributes(Filename) And IO.FileAttributes.Hidden) = IO.FileAttributes.Hidden Then
'Show the file.
IO.File.SetAttributes(Filename, IO.FileAttributes.Normal)
FileCounter = FileCounter + 1
End If
Next
For Each DirectoryName In Directories
If (IO.File.GetAttributes(DirectoryName) And IO.FileAttributes.Hidden) = IO.FileAttributes.Hidden Then
'Show the folder.
IO.File.SetAttributes(DirectoryName, IO.FileAttributes.Normal)
FolderCounter = FolderCounter + 1
End If
Next
End Sub

How to remove an item from a ListBox and line of text from TextFile referring to the same string

How would one remove an item from a ListBox and then remove that line from the TextFile and repopulate the ListBox with new data in Visual Basic.Net?
My source(apparently you can't have StreamReader and StreamWriter accessing the same file at the same time):
Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
Dim FILE_NAME As String = "C:\TextFile.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek <> -1
If objReader.ReadLine = recordLine Then
lstListBox.Items.RemoveAt(currentRecord)
numberOfRecords -= 1
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, False)
For i = 0 To numberOfRecords - 1
objWriter.WriteLine(lstListBox.Items(i))
Next i
objWriter.Close()
End If
Loop
lstListBox.Items.Clear()
numberOfRecords = 0
Do While objReader.Peek <> -1
lstListBox.Items.Add(objReader.ReadLine)
numberOfRecords += 1
Loop
objReader.Close()
Else
MsgBox("unknown error")
End If
End Sub
I'm very new to the VB.Net
Instead of StreamReader and StreamWriter you could just use FileStream and use a FileAccess type of ReadWrite. That way you can read and write at the same time.
It looks like the text file can be assumed to have the same lines as the listbox, since that is the way it ends up after this function. If that is the case, then you can delete the line from the listbox and then use it to write the text file.
Dim ss() As String
Dim i As Integer
Dim s As String
For Each s In ListBox1.Items
If s = recordLine Then
ListBox1.Items.Remove(s)
Exit For
End If
Next s
ReDim ss(ListBox1.Items.Count - 1)
For i = 0 To UBound(ss)
ss(i) = ListBox1.Items(i)
Next i
System.IO.File.WriteAllLines(FILE_NAME, ss)
If the listbox and text file can be different, then you can load the text file using ReadAllLines, remove the line from the array ss, then rewrite the text file using WriteAllLines.