Sub-folder inside folder on desktop - vb.net

I would like to create a sub-folder Y in a folder X which I already created on my desktop (see below).
Dim myFolder As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "X")
If (Not (System.IO.Directory.Exists(myFolder))) Then
System.IO.Directory.CreateDirectory(myFolder)
End If
I think I should use: System.IO.Directory.CreateDirectory(path), but what will be the path?
I don't know the syntax to use to create a folder "Y" inside the folder "X".
Maybe, path = My.Computer.FileSystem.SpecialDirectories.Desktop & "\X\", but nothing is created.

It may be easier than you think: Directory.CreateDirectory will create all the directories required, so you could use:
Dim myFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "X", "Y")
Directory.CreateDirectory(myFolder)
Or if you are using the .NET Framework 1.1 which only allows two items in Path.Combine:
Dim rootFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "X")
Dim myFolder = Path.Combine(rootFolder, "Y")
Directory.CreateDirectory(myFolder)
It is always worth looking at the documentation as it often includes useful comments about some common uses for a method.

OK, I found it. Just doing a double combination.
Thank you for your help.
JLuc01
Dim Folder As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "X")
Dim subFolder As String = IO.Path.Combine(Folder, "Y")
If (Not (System.IO.Directory.Exists(subFolder))) Then
System.IO.Directory.CreateDirectory(subFolder)
End If

Related

Delete A File That Contains The App Name (VB.NET)

This is the code I'm Using:
Dim file As String
Dim prefetchPath As String
Dim FileName As String = My.Application.Info.AssemblyName
prefetchPath = Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine) & "\Prefetch"
For Each file In IO.Directory.GetFiles(prefetchPath)
If file.Contains(FileName) Then
IO.File.Delete(file)
End If
Next
i don't know why it does not work if i use FileName. But it work if i use this code
If file.Contains("Example.exe") Then
IO.File.Delete(file)
End If
I want to make sure that if someone changes the name of the application the code works the same way(I already running the file as Administrator)
Help me Thanks.
My guess is that AssemblyName only returns the name without the extension, try including the .exe. Also, it is worth noting that you can use the IO.DirectoryInfo class and pass the file name in the GetFiles method to cut out your For/Each loop.
Here is a quick example:
Dim prefetchPath As String = IO.Path.Combine(Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine), "Prefetch")
Dim FileName As String = My.Application.Info.AssemblyName & ".exe"
If New IO.DirectoryInfo(prefetchPath).GetFiles(FileName).Count > 0 Then
IO.File.Delete(IO.Path.Combine(prefetchPath, FileName))
End If

Access vba Check if file exists

I have a database split in FrontEnd and BackEnd.
I have it running:
i) in my office
ii) updating/testing in my personal computer.
My BackEnd file is running in different Folder location according to computer running.
I want to place a code and check if file exist.
Code:
Sub FileExists()
Dim strPath As String '<== Office.
Dim strApplicationFolder As String
Dim strPathAdmin As String '<== Admin.
strPath = "\\iMac\Temp\"
strApplicationFolder = Application.CurrentProject.Path
strPathAdmin = strApplicationFolder & "\Temp\"
If Dir(strApplicationFolder & "SerialKey.txt") = "" Then
'===> Admin User.
If Dir(strPathAdmin & "*.*") = "" Then
'===> Empty Folder.
Else
'===> Files on folder.
End If
Else
'===> Office User.
If Dir(strPath & "*.*") = "" Then
'===> Empty Folder.
Else
'===> Files on folder.
End If
End If
End Sub()
I have this until now.
Any help.
Thank you...
Create a small function to check if a file exists and call it when needed.
Public Function FileExists(ByVal path_ As String) As Boolean
FileExists = (Len(Dir(path_)) > 0)
End Function
Since the backend database paths dont change, why dont you declare two constants and simply check their value?
Sub Exist()
Const workFolder As String = "C:\Work Folder\backend.accdb"
Const personalFolder As String = "D:\Personal Folder\backend.accdb"
If FileExists(workFolder) Then
'Work folder exists
End If
'....
If FileExists(personalFolder) Then
'Personal folder exists
End If
End Sub
This is a very belated reply, but don't reinvent the wheel. VBA can access the FileSystemObject, which includes a powerful set of methods that fetch file and folder information without requiring you to write your own functions, and the resulting code is much easier to read.
Second, borrowing on the previous answer, you know the folders you want the code to look at, and they don't change much, but because they could, I would also move your parameters into the declaration so they can be customized if needed or default to existing values.
Finally, FileExists is a verb, which should scream Function rather than Sub, so I'm guessing you want to return something and use it elsewhere in higher level code. It so happens that FileExists is already the name of a method in FileSystemObject, so I'm going to rename your function to LocatePath. You could return the valid path of the file you're looking for and decide by convention to quietly return an empty string "" if the target isn't found, and handle that in the calling procedure.
fs.BuildPath(strRootPath, strFileOrSubDir) appends strFileOrSubDir to strRootPath to construct a properly
formatted, full pathname and you don't need to worry about
whether you have backslashes (or too many) between the two.
It can be used to append files, or subdirectories, or
files in subdirectories.
fs.FileExists(strFullPath) is simple, returns True if strFullPath exists,
and False otherwise.
fs.GetFolder(strFolderName) returns a Folder object that has a
.Files property, which is a Collection object. Collection
objects in turn have a .Count property, which in this example
indicates how many files are in strFolderName. The Collection
object could also be used to iterate over all the files in the
folder individually.
What follows is your code refactored to incorporate all the changes I recommend according to what I think you're trying to achieve. It's not as symmetric as I'd like, but mirrors your code, and it's simple, easy to read, and finished in the sense that it does something.
Function LocatePath(Optional strWorkPath as String = "\\iMac",
Optional strHomePath as String = CurrentProject.Path,
Optional strFile as String = "SerialKey.txt"
Optional strSubDir as String = "Temp") as String
Dim fs as Object
Set fs = CreateObject("Scripting.FileSystemObject")
If fs.FileExists(fs.BuildPath(strHomePath, strFile)) Then
If fs.GetFolder(fs.BuildPath(strHomePath, strSubDir).Files.Count > 0 Then '===> Admin User.
LocatePath = fs.BuildPath(strHomePath, strFile)
ElseIf fs.GetFolder(fs.BuildPath(strWorkPath, strSubDir).Files.Count > 0 Then '===> Office User
LocatePath = fs.BuildPath(strWorkPath, strFile)
End If
Else 'Target conditions not found
LocatePath = ""
End If
Set fs = Nothing
End Function()
Ideally, I probably wouldn't specify strHomePath as String = CurrentProject.Path because strWorkPath as String = CurrentProject.Path is probably also true when you're at work, and you would want to do a better job of differentiating between the two environments. This is also what causes the little problem with symmetry that I mentioned.

VB NET - CopyDirectory only copies files? Why?

I have been trying to do this seemingly simple task for a while now, but no luck. Here is some pieces of code I'm using...
Dim SDPath As String = TextBox1.Text
Dim ContentPath As String = TextBox2.Text
Dim RPXName As String = TextBox4.Text
Dim Copy_To_Dir As String = SDPath & RPXName
Dim Copy_To_Dir As String = SDPath & RPXName
'copy any subdirs from ContentDir to SD:\RPXName
For Each ContentDirSub In System.IO.Directory.GetDirectories(ContentPath, "*", IO.SearchOption.AllDirectories)
My.Computer.FileSystem.CopyDirectory(ContentDirSub, Copy_To_Dir, True)
Next
This should create the sub directories in the specific path. Where am I going wrong here??? I've been scouring examples but found nothing. I also want this to copy the contents of the sub directory as well.
Not sure why it isn't working but you could try to make sure that the path you are copying to is a correct directory path. The below code combines the path into a correct path name.
Dim Copy_To_Dir As String = System.IO.Path.Combine(SDPath & RPXName)
You also don't need to write that twice.
Is there any errors appearing?

Comparing files in list of string to files in target directory

I have searched this issue for 2 days, without finding a solution. I might be using the wrong search terms, due to my limited knowledge of the subject.
I have 2 folders, a source and a target, each with files in them. I need to compare the files in these 2 dirs and delete the duplicate files from the target dir before moving the files from the source dir.
I have created a list of string for both dirs. But I can't seem to figure out how to make the dupes in the targetdir to get deleted instead of from the list itself. However, if I put targetdir or sourcedir in the File.Exists() and File.Delete(), it doesn't see the files.
My code is below. Can anyone help me with this?
Dim sourcedir As String
sourcedir = TextBox1.Text + "\"
Dim targetdir As String
targetdir = readValue + "\"
For Each filename In filelist
If System.IO.File.Exists(filename) Then
System.IO.File.Delete(filename)
End If
Next
Edit:
Thank you so very much. This is the code that I used, in case someone else has the same issue.
Dim sourcedir As String
sourcedir = TextBox1.Text + "\"
Dim targetdir As String
targetdir = readValue + "\"
Dim sourceFilePaths = My.Computer.FileSystem.GetFiles(sourcedir, FileIO.SearchOption.SearchAllSubDirectories)
Dim targetFilePaths = My.Computer.FileSystem.GetFiles(targetdir, FileIO.SearchOption.SearchAllSubDirectories)
'Compare only file names, ignoring paths, and get a list of duplicates.
Dim duplicateFileNames = sourceFilePaths.Select(Function(filePath) System.IO.Path.GetFileName(filePath)).
Intersect(targetFilePaths.Select(Function(filePath) System.IO.Path.GetFileName(filePath)))
'Combine target folder path with duplciate file names and delete each one.
For Each filePath In duplicateFileNames.Select(Function(fileName) System.IO.Path.Combine(targetdir, fileName))
System.IO.File.Delete(filePath)
Application.DoEvents()
Next
E.g.
Dim sourceFolderPath = "C:\SourceFolder"
Dim targetFolderPath = "C:\TargetFolder"
Dim sourceFilePaths = Directory.GetFiles(sourceFolderPath)
Dim targetFilePaths = Directory.GetFiles(targetFolderPath)
'Compare only file names, ignoring paths, and get a list of duplicates.
Dim duplicateFileNames = sourceFilePaths.Select(Function(filePath) Path.GetFileName(filePath)).
Intersect(targetFilePaths.Select(Function(filePath) Path.GetFileName(filePath)))
'Combine target folder path with duplciate file names and delete each one.
For Each filePath In duplicateFileNames.Select(Function(fileName) Path.Combine(targetFolderPath, fileName))
File.Delete(filePath)
Next
Here's an option that doesn't use LINQ:
Dim sourceFolderPath = "C:\SourceFolder"
Dim targetFolderPath = "C:\TargetFolder"
Dim sourceFilePaths = Directory.GetFiles(sourceFolderPath)
Dim targetFilePaths = Directory.GetFiles(targetFolderPath)
Dim sourceFileNames As New List(Of String)
For Each sourceFilePath In sourceFilePaths
sourceFileNames.Add(Path.GetFileName(sourceFilePath))
Next
For Each targetFilePath In targetFilePaths
Dim targetFileName = Path.GetFileName(targetFilePath)
If sourceFileNames.Contains(targetFileName) Then
File.Delete(targetFilePath)
End If
Next
It's important to note that both these examples are case-sensitive. Both the Intersect and Contains methods will accept an IEqualityComparer(Of String) though, so you can provide one to make them case-insensitive.

VB.net use string in Directory Path?

I apologise for my lack of basic VB.net knowledge but I'm looking to use the equivalent of %systemdrive% to find the drive containing Windows to check for an existing directory in VB.net - so I have the below.
Dim systemPath As String = Mid(Environment.GetFolderPath(Environment.SpecialFolder.System), 1, 3)
If Not Directory.Exists("'systemPath'\MyFolder") Then
Directory.CreateDirectory("'systemPath'\MyFolder")
End If
Can someone help with using the systemPath string in the directory query? Thank you.
Well you should write
Dim systemPath As String = Mid(Environment.GetFolderPath(Environment.SpecialFolder.System), 1, 3)
If Not Directory.Exists(Path.Combine(systemPath, "MyFolder")) Then
Directory.CreateDirectory(Path.Combine(systemPath, "MyFolder"))
End If
You could get the environment variable called %SYSTEMDRIVE% with Environment.GetEnvironmentVariable, but then the results obtained should be manually combined with current directory separator char ("\") because I have not found any way to convince Path.Combine to build a valid path with only the system drive (I.E. C: )
Dim sysDrive = Environment.GetEnvironmentVariable("SystemDrive")
Dim myPath = sysDrive & Path.DirectorySeparatorChar & "MyFolder"
IO.Path has methods that should be used IMHO
Dim sysDrive As String = Environment.GetEnvironmentVariable("SystemDrive") & IO.Path.DirectorySeparatorChar
Dim myPath As String = IO.Path.Combine(sysDrive, "FolderName")