Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vb.net

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
like image 282
Marco Avatar asked Sep 04 '12 05:09

Marco


People also ask

How do I get the fileName from the file path?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);

Which of these shows the name of a file in VB?

Answer: The title bar displays the name of the application and file name being used in the window.

How do I find the name of a file object?

The getName() method is a part of File class. This function returns the Name of the given file object. The function returns a string object which contains the Name of the given file object.

What is the method to find the path of file in Visual Basic?

Use the DirectoryName and Name properties of the FileInfo object to determine a file's name and path.


1 Answers

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)

like image 96
Tim Schmelter Avatar answered Oct 06 '22 22:10

Tim Schmelter