rename Renamed file already exist - vb.net-2010

i have a problem with renaming a duplicate file in a folder. How to skip it so that only the original file is renamed?
here is my code:
For i As Integer = 0 To ListView1.Items.Count - 1
My.Computer.FileSystem.RenameFile(ListView1.Items(i).Text, TextBox7.Text)
next

There is inherent mistake in the code. You are trying to give same name to multiple files. As per your code, each item of ListView1 obtained through ListView1.Items(i).Text will be renamed to text mentioned in TextBox7.Text.
The loop itself is wrong.

Related

vb.net wildcard file search exception

im totally new to vb.net
I figured how to find files using wildcard and it works fine but i need error meassage if file not found.
here's my code.
any help highly appreciated !
For Each hist In Directory.GetFiles("C:\temp", "*.*", SearchOption.TopDirectoryOnly)
If File.Exists(hist) Then
File.Copy(hist, Path.Combine("C:\temp\1", Path.GetFileName(hist)), True)
MessageBox.Show("file exist and copied") <-- this message shows up and files are copied
Else
MessageBox.Show("No files. Folder is empty !") <--this message never shows up when folder is empty . no files at all
End If
Next
It is unlikely you would see that second message. You are grabbing the list of files from the OS directly - so, at least at the time that you retrieve the file name that file exists. If you wanted to simulate a case where the file doesn't exist, place a break point on the IF File.Exists(hist) Then line. While the program is paused there, go find and delete whatever the current file is. Then continue the program.
i got it working.
here's what i added before foreach :
Dim myDir As DirectoryInfo = New DirectoryInfo("c:\temp\")
If (myDir.EnumerateFiles().Any()) Then
foreach ....
else
MessageBox.Show("no files in directory ") <-- my message
thanks for advice!!

Copy and Delete File Leaves Zero Length File at Source

I'm trying to copy a file from one directory to another. After the copy, I want to delete the original file. The expected result is that the source file no longer exists and the destination file does exist. The actual result is that the destination file exists and that an empty source file exists. Watching the directory during execution, the source file initially disappears then upon exiting the program it reappears with a length of zero.
Here's sample code:
Imports System.IO
Module Module1
Sub Main()
Dim sourceFileName As String = "c:\TestDir\source\TestFile.txt"
Dim destFileName As String = "c:\TestDir\destination\TestFile.txt"
System.IO.File.Copy(sourceFileName, destFileName)
System.IO.File.Delete(sourceFileName)
End Sub
End Module
If I were to remove the System.IO.Copy, the zero-length file does not appear. So it seems to have something to do with the combination of copying and deleting.
Are my expectations amiss? I realize I can delete the destination if it exists then Move the file, but I would like to understand why my sample does not work as I expect it. Thanks for any insight.
Try using the FileSystem.DeleteFile method from here:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.fileio.filesystem.deletefile?view=netframework-4.7.2
This should completely remove the file.
Has the Read-Only attribute been applied to your test file? If so, you can try something like this:
File.Copy(sourceFileName, destFileName)
File.SetAttributes(sourceFileName, FileAttributes.Normal);
File.Delete(sourceFileName)
Is there a reason you're not just using File.Move?

Retrieve the name of the most recent file in a directory using VB.Net

Let's say I am looking for a file that has a name that starts with GLNO1_
I can have hundreds of files that start with those characters, but I want to retrieve the name of the file that starts with those characters that is the most recently modified.
For example, Lets say I have files GLNo1_1, GLNo1_2, GLNo1_3 etc. up to _1000
and number 556 is the file that was modified the most recent.
In VB.Net, how do I retrieve that file name.
The file extensions are of .csv
You'll have to enumerate the files and pick the last one. That's a job for Linq:
Dim dir = New System.IO.DirectoryInfo("c:\foo\bar")
Dim file = dir.EnumerateFiles("GLNo1_*.csv").
OrderByDescending(Function(f) f.LastWriteTime).
FirstOrDefault()
If file IsNot Nothing Then
Dim path = file.FullName
'' etc..
End If
Never overlook the odds that there will be more than one "last one". If your program hasn't run for a while then more than one file could easily have been added by whatever software generates the *.csv files. You generally need to keep track of the files you've already seen before.

Visual Basic FileSystem.GetFiles

I'm making a console application and I want to see what files is in a folder
For Each foundFile As String In My.Computer.FileSystem.GetFiles("c:\users\zac\desktop\booked vehicle\requested\")
Console.WriteLine(foundFile)
Next
after using this code and find that the folder is empty I need an If statement that say's
If foundfile has no files then
tell user no files found
end if
but I don't know how to write this so Visual Basic understands.
Load the files into a variable then check the count.
Dim files = My.Computer.FileSystem.GetFiles("c:\users\zac\desktop\booked vehicle\requested\")
If files.Count = 0 Then
'tell user no files
Else
For Each file In files
Console.WriteLine(file)
Next
End If
FileSystem.GetFiles() returns a collection of file name strings. As OneFineDay showed, you can use the collection's Count property to know if any files were found.
The downside of using FileSystem.GetFile() is that it has to search the entire folder before then returning the entire list of filenames. If you are searching large folders and speed is an issue, consider using Directory.EnumerateFiles() instead. That way, you can output a message if no file was found, otherwise loop throuh the list of found files. For example:
Dim files = Directory.EnumerateFiles("c:\users\zac\desktop\booked vehicle\requested\").GetEnumerator()
If files.MoveNext Then
' files were found
Do
Console.WriteLine(files.Current)
Loop Until Not files.MoveNext
Else
' no files were found
End If
I personally would use Linq to accomplish this. It's very quick and efficient to use in this case. I put the Console.ReadLine() at the end to show the files, you can remove this if need to be. Also you can change the Console.WriteLine to not include the string (s) if you don't want to. The s was declared if you want to show the files and also to see if there are any files. As I said, this was for my viewing to see the files. Straight to the point!
Dim s As String = String.Join(Environment.NewLine, New DirectoryInfo("YOUR DIRECTORY").GetFiles().[Select](Function(file) file.Name).ToArray)
Console.WriteLine(If(s.Length > 0, s, "No files found!"))
Console.ReadLine()

Moving and Deleting Files in a Loop in VB.Net

I'm trying to improve a system I have that already works. However I've ran into a problem I can't seem to find an answer to using google, perhaps I'm not searching the right questions?
I'm using a For Each loop to gather files in a directory. I then try to get each file name and some other information and determine if I should move the file temporarily or delete the file.
Example of the code used:
For Each File In Directory.GetFiles(Profile)
Dim tmpFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(File) 'Never moves to the next file.
Dim Name As String = tmpFile.Name
Dim AccessDate As String = tmpFile.LastWriteTime.Date()
Dim CurrentDate As String = My.Computer.Clock.LocalTime.Date()
If AccessDate < CurrentDate Then
My.Computer.FileSystem.DeleteFile(File) 'Moves to the next file without any issues.
Threading.Thread.Sleep(150) 'If no sleep program will lock up
Else
If Not Directory.Exists(Path) Then
Directory.CreateDirectory(Path)
My.Computer.FileSystem.MoveFile(File, Path & Name)
Else
My.Computer.FileSystem.MoveFile(File, Path & Name)
End If
End If
Next
I have defined in the code what my problem is, and forgive me if there is a better way to do this, I'm self taught and still learning many things. If there's an easier way please point me in that direction.
Essentially I hit an error saying "File not found" on the move because tmpFile is not moving to the next File in the directory.