replace file name have multiple extensions in vb.net - vb.net

I have an issue while uploading documents have multiple periods. For example if I upload a file having an extension of ammu.gopu.docx. I would like to replace that as ammu_gopu.docx, means to preserve the extension and replace the file name with undescore.

This should do what your asking. Beware - If your file name also appears in the path it will also be updated.
Dim fullPath As String = "C:\Test\My.File.Name.txt"
Dim fileName As String = IO.Path.GetFileNameWithoutExtension(fullPath)
fullPath = fullPath.Replace(fileName, fileName.Replace("."c, "-"))

Use the System.IO.Path.GetExtension method.

Try this:
filePath = IO.Path.GetDirectoryName(filePath) & _
IO.Path.GetFileNameWithoutExtension(filePath).Replace("."c, "_"c) & _
"." & IO.Path.GetExtension(filePath)

Related

Opening an excel file with partial name

Is there a way to open an excel file without knowing the full path name?
For example:
TEST_03222018.csv is the file name located in C:\test\folder
the known part of the string\path is
C:\test\folder\TEST_03
is there a way to open this csv sheet without the rest of the path (preferably without using InStr() or any If, While loops
Function findFile(strFileStart as string) as string
findFile= Dir(strFileStart & "*", vbNormal)
End Function
Echo, #Ryan Wilson's comments about having more than one file with the same prefix though.
Use Dir with a wildcard to confirm the existence and if found, open it.
dim fp as string, fn as string
fp = "C:\test\folder\"
fn = "test_03"
fn = dir(fp & fn & "*.csv")
if cbool(len(fn)) then
workbooks.open fp & fn, delimiter:=","
end if

StreamWriter Text File name must include hour, minute and second

Run following code and see that you have text file on the desktop named MyLogFile 08.04.2017
Dim Log As System.IO.StreamWriter
Log = My.Computer.FileSystem.OpenTextFileWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\MyLogFile " & System.DateTime.Now.Date.ToString("dd/MM/yyyy") & ".txt", False)
Log.WriteLine("Hello")
Log.Close()
I had wanted to change file name from MyLogFile 08.04.2017 to MyLogFile 08.04.2017 07:50:59 but it is not possible because : is not allowed.
Now, I want to change file name from MyLogFile 08.04.2017 to MyLogFile 08.04.2017 07.50.59 thanks to your support.
I would strongly recommend that, when including dates and time in file and folder names, that you go from most significant to least significant. The reason for that is that then alphabetical and chronological order will match. Personally, I don't use separators at all so that would be:
Log = My.Computer.FileSystem.OpenTextFileWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
String.Format("MyLogFile.{0:yyyyMMddHHmmss}.txt",
Date.Now),
False)
If you really want to do it your way then it would be:
Log = My.Computer.FileSystem.OpenTextFileWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
String.Format("MyLogFile {0:dd.MM.yyyy HH.mm.ss}.txt",
Date.Now),
False)
You simply change the format specifier as needed.
You could do:
Dim Folder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim FileName As String = "MyLogFile " & DateTime.Now.ToString("dd.MM.yyyy HH.mm.ss") & ".txt"
Dim Log As System.IO.StreamWriter
Log = My.Computer.FileSystem.OpenTextFileWriter(System.IO.Path.Combine(Folder, FileName), False)
Log.WriteLine("Hello")
Log.Close()

How to list only file name?

I have program to find files in a directory and list them in a listbox, but the following code I'm using adds the full path for the file found.
Is there something I'm missing to make it only add the file name and not the full path?
If My.Computer.FileSystem.DirectoryExists(My.Computer.FileSystem.CurrentDirectory & "\" & Details.IDL.Text) Then
For Each FoundFile As String In My.Computer.FileSystem.GetFiles(My.Computer.FileSystem.CurrentDirectory & "\" & Details.IDL.Text)
ListBox.Items.Add(FoundFile)
Next
Else
My.Computer.FileSystem.CreateDirectory(My.Computer.FileSystem.CurrentDirectory & "\" & Details.IDL.Text)
End If
so to fix it i only had to put ListBox.Items.Add(IO.Path.GetFileName(FoundFile)) instead of ListBox.Items.Add(FoundFile)
Here is a working example to list file name individually with GetFileNameWithoutExtension, along with the way you are using GetFileName.
Dim fileName As String = "C:\mydir\myfile.ext"
Dim pathname As String = "C:\mydir\"
Dim result As String
result = Path.GetFileNameWithoutExtension(fileName)
Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'", fileName, result)
result = Path.GetFileName(pathname)
Console.WriteLine("GetFileName('{0}') returns '{1}'", pathname, result)

Get and edit a file name

I'm looking to retreive a txt file and then edit the file name (adding "converted" to the file name) and extension (from .r01 to .txt).
The purpose for this is so I can know if the txt file has been converted
Here's my code so far;
Dim infilename As Variant
infilename = Application.GetOpenFilename("Text & r01 Files (*.r01;*.txt),*.r01;*.txt", , "Open Neutral File", "OPEN")
InStrRev will allow you to find the last . and remove it and everything following from the string
FileNameWithoutExt = Left(Filename, InStrRev(Filename, ".") - 1)
An example with the workbooks FullName:
?activeworkbook.FullName
Z:\Individual Folders\Sean\transfers2.xlsx
?Left(activeworkbook.FullName, InStrRev(activeworkbook.FullName, ".") - 1)
Z:\Individual Folders\Sean\transfers2
You can wrap these in a function to make them easier to use. I've also added a function that will give the filename only instead of the one with the full path
Function FileNameOnly(fName)
'Changes "C:\Path\Filename.ext" to "Filename.ext"
FileNameOnly=mid(fName,instrrev(fName,"\")+1)
End Function
Function DelExt(fName)
'Changes "C:\Path\Filename.ext" to "C:\Path\Filename"
DelExt=left(fName,instrrev(fName,".")-1)
End Function
You can then use these in your program, with a line like NewFileName=DelExt(infilename) & "CONVERTED.txt"
I managed to get what I was looking for using part of Sean Cheshire's code.
Dim newFileName As Variant
newFileName = Left(inFileName, (InStrRev(inFileName, ".") - 1)) & "CONVERTED.txt"

How to know the path in System.Web.HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath)

strFilePath = System.Web.HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath)
strFilePath = str + "ApInterface_" + Format(Now.Date, "dd-MMM-yyyy").Replace("-", "") + "_" + Format(Now, "HH:mm:ss").Replace(":", "") + ".dat"
I have the above code snippet where it saves the file in .dat extension in the specified folder. The problem for me is about the path. When I specify the path something like "D:\myfolder", the data will be exported and file will be opened but it wont get saved. If I specify the folder as "D:\myfolder\" it saves perfectly, why do I need "\" and the end?
Use Path.Combine instead of string concatenation. It will add the slashes as they are needed.
Shouldn't your code be something like this:
strFilePath = System.Web.HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath)
strFilePath = strFilePath + "ApInterface_" + Format(Now.Date, "dd-MMM-yyyy").Replace("-", "") + "_" + Format(Now, "HH:mm:ss").Replace(":", "") + ".dat"
As it stands, there is no explanation of what "str" holds.
Assuming the above is correct, the reason you need the "\" is because without it there are two distinctly different paths:
D:\myfolderApInterface_01012001_010101.dat
D:\myfolder\ApInterface_01012001_010101.dat
The first references a file called "myfolderApInterface_01012001_010101.dat" in the root directory of the "D" drive, while the second references a file called "ApInterface_01012001_010101.dat" in the "myfolder" directory of the "D" drive.
As someone else has mentioned, you can use Path.Combine which will work out whether a "\" is already present and add it in only if needed.
P.S. You may also want to consider using string.Format to build up your filename to improve readability