File is a directory not a file - vb.net

I have a folder called test which has subfolders: A, B, and C at the root. I am trying to copy a file to these three folders.
Not sure why the I am getting the error:
The target file "c:\test\A" is a directory and not a file. Please help.
Dim OPUSINI As New FileInfo("C:\Program Files (x86)\OPUS_4.5\OPUS32.INI")
'Where is will be going
'Dim Win7DestLocation As String = "C:\Users"
Dim Win7DestLocation As String = "C:\test"
Dim WinXPDestLocation As String = "C:\Documents and Settings"
'Get a list of all the Subfolders within the Destination location
Dim Win7Destdir As New DirectoryInfo(Win7DestLocation)
Dim WinXPDestdir As New DirectoryInfo(WinXPDestLocation)
'Checks if Destination Exists for Windows 7
Dim Win7CheckExistDestLocation As New IO.DirectoryInfo(Win7DestLocation)
'Checks if Destination Exists for Windows XP
Dim WinXPCheckExistDestLocation As New IO.DirectoryInfo(WinXPDestLocation)
If Win7CheckExistDestLocation.Exists Then
Try
For Each subfolder As DirectoryInfo In Win7Destdir.GetDirectories
OPUSINI.CopyTo(subfolder.FullName, True)
Next
Catch ex As Exception
MessageBox.Show("Unable to backup Pump data files." + ex.ToString, "Backup Error:", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

You are passing a directory name to CopyTo.
That method wants a filename not a directory name.
Thus the exception received.
If I understand your code well, you need to change that line to
Dim destFile = Path.Combine(subfolder.FullName, OPUSINI.Name))
OPUSINI.CopyTo(destFile, True)
Also using DirectoryInfo objects is not really necessary here.
The simple Directory class could do the same things with less overhead

Related

Move directory and it's content vb.net

I would like to move the folder and its contents to another directory. This means the folder and contents will no longer exist from the source and will be moved to its destination. But when the destination path has the same folder name, it will just overwrite the folder and its content.
I'm getting error if same folder exists in the destination path using the code below.
The catch here is I don't exactly know the folder name and filename here inside the source path. I just know where I'm going to get the folder and files to move to its destination.
I've used these codes but couldn't figure out how to overwrite:
'web.config
Sourcepath = "C:\TestSource\"
Destinationpath = "C:TestDestiation\"
'calling the move function:
dInfoSource = New DirectoryInfo(ccConfigClass.SourcePath)
dInfoDestination = New DirectoryInfo(ccConfigClass.DestinationPath)
MoveContents(dInfoSource, dInfoDestination)
Public Sub MoveContents(sourcePath As DirectoryInfo, destinationPath As DirectoryInfo)
Try
If (Not destinationPath.Exists) Then
destinationPath.Create()
End If
'Move all Files
For Each file As FileInfo In sourcePath.GetFiles()
file.MoveTo(Path.Combine(destinationPath.FullName, file.Name))
Next
'Move all folders
For Each dir As DirectoryInfo In sourcePath.GetDirectories()
dir.MoveTo(Path.Combine(destinationPath.FullName, dir.Name))
Next
Catch ex As Exception
Dim objErrorLogger As New ErrorLogging
objErrorLogger.LogError(_CLASS_NAME, Reflection.MethodInfo.GetCurrentMethod.Name, ex.Message.ToString, ex)
End Try
End Sub

Can multiple files be moved in as a batch

I want to move multiple files from one directoy to anoher. I use 'My.Computer.FileSystem.MoveFile' and that works fine but it handles one file at a time. So, for every already existing file in that directory I get a warning (ie. 'File already exists') instead of one warning for the batch. Is it posible to get one warning for all the moved files?
For i = .Items.Count - 1 To 0 Step -1
Dim map = .Items.Item(i).SubItems(COL_MAP).Text
Dim bestandHernoemd = .Items.Item(i).SubItems(COL_HERNOEMD).Text
Dim bestandOrigineel = .Items.Item(i).SubItems(COL_ORIGINEEL).Text
Try
My.Computer.FileSystem.MoveFile(map & bestandOrigineel, My.Settings.OPTIE_OvernemenStandaardMapNaam & bestandHernoemd, Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException)
.Items.RemoveAt(i)
Catch ex As Exception
foutLijst.Add(bestandOrigineel & ": " & ex.Message)
End Try
Next
And if you want to copy files recursively ( all folders, subfolders, files or subfiles ) from one source to destination, you can use the below sub procedure. No Warning applied and shall overwrite the destination.
Public Sub CopyDirectory(ByVal sourcePath As String, ByVal destinationPath As String)
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePath)
'If the destination folder doesn't exist then create it'
If Not System.IO.Directory.Exists(destinationPath) Then
'Obs, folder doesn't exist, create one please :)'
System.IO.Directory.CreateDirectory(destinationPath)
End If
Dim fileSystemInfo As System.IO.FileSystemInfo
For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
Dim destinationFileName As String = System.IO.Path.Combine(destinationPath, fileSystemInfo.Name)
'Now check whether its a file or a folder and take action accordingly
If TypeOf fileSystemInfo Is System.IO.FileInfo Then
System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, True)
Else
' Recursively call the method to copy all the nested folders
CopyDirectory(fileSystemInfo.FullName, destinationFileName)
End If
Next
End Sub

VB.NET file error 75 - Path/File Access Error - how is my file locked? I need to delete it

i'm getting a error 75 - file/path access error when i attempt to delete my file (last lines of the code block below):
' make a reference to a directory
Dim directory As New IO.DirectoryInfo(WatchDirectory) 'ex C:\Print\Realtime\
Dim directoryList As IO.FileInfo() = directory.GetFiles(WatchFilter) 'ex *.xml
Dim directoryFile As IO.FileInfo
'list the names of all files in the specified directory
For Each directoryFile In directoryList
'scans the Realtime folder (WatchDirectory) for each specified file (WatchFilter / xml) for processing.
If directoryFile.Name = RealTimeFile Then
'checks if the file is realtime by matching the name up to the ProcessRealtimeFile app setting (ex realtime.xml)
Continue For
Else
'this is not a ProcessRealtimeFile app setting (ex realtime.xml) file
Dim Name As String
Dim renameRetries As Integer = 5
'get file name without extension
Name = IO.Path.GetFileNameWithoutExtension(directoryFile.Name)
While True
Try
If File.Exists(ProcessDirectory & RealTimeFile) = False Then
'the current file to be checked against in the watch directory does not exist in the processdirectory (ex. C:\Print\Oracle\xml.rt\). continue.
Log.Write(Log.Level.Information, "RTPrint-Diamond", Environment.UserName, Environment.MachineName, "File " & directoryFile.FullName & " is being processed by scrape.")
If ArchiveXML = True Then
'copy the current file to the archive directory (ex C:\print\xml.rt\archive\), overwriting the existing file if exists
System.IO.File.Copy(directoryFile.FullName, ArchiveDirectory & directoryFile.Name, True)
End If
'update the date and time of the active file to now
System.IO.File.SetLastWriteTime(directoryFile.FullName, Date.Now)
Log.Write(Log.Level.Information, "RTPrint-Diamond", Environment.UserName, Environment.MachineName, "Date Changed.")
If ISPublisher(directoryFile.FullName) Then
'Current file is a publisher file. Process
Dim fileInfo As New IO.FileInfo(directoryFile.FullName)
Dim utf8WithoutBOM As New System.Text.UTF8Encoding(False) 'file encoding type - UTF8 w/o BOM
Using writer As StreamWriter = New StreamWriter(Path.Combine(PublisherProcessDirectory, directoryFile.Name), False, utf8WithoutBOM)
'set up write to the publisher process directory (ex C:\print5x\xml.rt\)
'publisher requires utf8 w/o BOM to read the file. We need to change the encoding type to this standard.
'this converts the file to utf8 w/o BOM to the 5x output destination
Using reader As StreamReader = fileInfo.OpenText
While Not reader.EndOfStream
Dim line As String = reader.ReadLine
writer.Write(line & vbCrLf)
End While
reader.Close()
End Using
writer.Close()
End Using
If File.Exists(Path.Combine(PublisherProcessDirectory, directoryFile.Name)) Then
'make sure the destination file was successfully re-written in utf8 w/o bom and delete the source file
If IsFileOpen(directoryFile.FullName, 1) = True Then
Microsoft.VisualBasic.FileClose(1)
End If
System.IO.File.Delete(directoryFile.FullName)
End If
I even tested with some sample solutions I read on this site to run a function test to see if the lock is present (giving error 75), and if true is returned, attempt a file close which also is not doing anything.
Obviously my writer.Close() is not doing the job. Can anyone spot why the System.IO.File.Delete(directoryFile.FullName) is not allowing me access to this text file for deletion, and how i can unlock it to delete? Is it the for each that is locking my file? I need to delete the file within the loop, so if the for loop is locking me, what are the work-arounds here?
Additionally, i tested the delete by removing the entire writer block and 2 declared variables above it, and the file still had a lock. This can help to isolate the issue to the surrounding logic and not the streamWriter portion.
Thanks in advance!

How to move all files and folders from current directory to another directory excluding a folder named "My Folder" in vb?

I want to move all files and folders from current directory to another directory excluding a folder named "My Folder". I want to know how can I do this with vb?
Not really tested but might be helpful anyway:
Dim currentDir = Directory.GetCurrentDirectory() ' or whatever you call current
Dim targetDir = Path.Combine(currentDir, "Target-Directory")
Directory.CreateDirectory(targetDir)
Dim allDirs = From dir In Directory.EnumerateDirectories(currentDir, "*.*", SearchOption.AllDirectories)
Where Not Path.GetFileName(dir).Equals("My Folder", StringComparison.InvariantCultureIgnoreCase)
For Each dir As String In allDirs
Try
Dim targetPath As String = Path.Combine(targetDir, Path.GetFileName(dir))
Directory.Move(dir, targetPath)
Catch ex As Exception
' log or whatever, here just ignore and continue ...
End Try
Next
'now move the rest of the files in the troot folder
Dim filesInRoot = From file In Directory.EnumerateFiles(currentDir, "*.*", SearchOption.TopDirectoryOnly)
For Each file As String In filesInRoot
Try
Dim targetPath As String = Path.Combine(targetDir, Path.GetFileName(file))
IO.File.Move(file, targetPath)
Catch ex As Exception
' log or whatever, here just ignore and continue ...
End Try
Next

Copy files in VB.NET

I'm trying to create an installer-like application. Here is what its supposed to do: create a directory in C: and name it batch. Then copy the files from the folder and move it to the C:\batch directory. But the copying of files doesn't work.
How am I supposed to put the exact directory in here if that exact directory does not apply to all? What do I do with it? If the file that is to be copied is from: E:\Documents and Settings\Rew\My Documents\Visual Studio 2008\Projects\batch\batch
I want it to be universal. So that wherever the file maybe it could always copy it regardless of where it is located.
Somehow the creating of a directory work.
Dim FileToCopy As String
Dim NewCopy As String
Try
Directory.CreateDirectory("C:\Batch")
FileToCopy = "\batch\batch\ipconfigrenew.bat"
FileToCopy = "\batch\batch\ipconfigrelease.bat"
FileToCopy = "\batch\batch\ipconfigflushdns.bat"
NewCopy = "C:\Batch"
If System.IO.File.Exists(FileToCopy) = True Then
System.IO.File.Copy(FileToCopy, NewCopy)
MsgBox("File Copied")
End If
Catch
End Try
MsgBox("Done")
First, the only value in FileToCopy by the time you do the copy is the last one. I'm having trouble parsing the question to figure out what you need, but I would first do this:
Dim FileToCopy(3) As String
FileToCopy(0) = "\batch\batch\ipconfigrenew.bat"
FileToCopy(1) = "\batch\batch\ipconfigrelease.bat"
FileToCopy(2) = "\batch\batch\ipconfigflushdns.bat"
Dim NewCopy As String = "C:\Batch"
Dim s As String
For Each s In FileToCopy
If System.IO.File.Exists(s) = True Then
System.IO.File.Copy(s, NewCopy)
MsgBox("File Copied")
End If
Next
Next, I would decide if I needed to write this in a more generic way.