I want to check if sub-folder exists or not. If exists, move on. If not exists go to next task.
My sub-folder is "C:\Folder1\Folder2\Folder3" I want to check if Folder3 is exists or not.
I worked on it. Create 2 variables
1> FolderPath = C:\Folder1\Folder2
2> FolderExists = Boolean = False
Script Task
ReadOnlyVariable = #FolderPAth
ReadWriteVariable = #FolderExists
Following script I add in edit script
Dim DirExists As String
DirExists = Dir(CStr(Dts.Variables("Folder3").Value))
If DirExists <> "" Then
Dts.Variables("Folder3").Value = True
Else
Dts.Variables("Folder3").Value = False
End If
Can some one correct me please.
Based on your comment it doesn't seem like you will care if it is c# of VB so here are steps from beginning to end on how to test Existence of a folder and use it in constrained precedence.
Define 2 Package Level Variables: FolderPath string, FolderExists boolean
Add Script Task and configure for C# and add FolderPath as a ReadOnlyVariable and FolderExists as a ReadWriteVariable
Click Edit to Edit the script
Scroll to "#region Namespaces" near the top and add using System.IO;
Scroll to the definition of the Main() sub and add the first line after "TODO" below so that the routine becomes:
public void Main()
{
// TODO: Add your code here
Dts.Variables["User::FolderExists"].Value = Directory.Exists(Dts.Variables["User::FolderPath"].Value.ToString());
Dts.TaskResult = (int)ScriptResults.Success;
}
The script task is complete and you should now be able to use the FolderExists variable as the expression for constrained precedence.
Add your next step in the package and connect with the green success arrow then double click the arrow and set the Constraint Options to evaluate for Expression and Constraint and the expression simply as the FolderExists variable.
this solution was fully tested and is operational
Related
I want to delete all the files contained in a folder. The below code does delete the file but also deletes the folder itself. I am aware you will need to perform a for loop to remove each item from the folder, but can't find the information on how to start the code for it. Can someone point me in the correct direction.
Dim folderFiles() As String
folderFiles= Directory.GetFileSystemEntries("C:\New Folder")
For Each element As String In files
If (Not Directory.Exists(folder)) Then
File.Delete(Path.Combine("C:\New Folder", Path.GetFileName(folder)))
End If
Next
This is the easier way :
For Each the_file As String In Directory.GetFileSystemEntries("C:\New folder")
File.Delete(the_file)
Next
Don't bother to grab the list of files and then browse it, use your loop directly on it.
I have a function for that. With it, you can also delete all files of a pattern even for all subdirectories:
Public Sub DeleteFiles(Path As String,
Optional Pattern As String = "*.*",
Optional All As Boolean = False)
Dim SO As IO.SearchOption = If(All, IO.SearchOption.AllDirectories, IO.SearchOption.TopDirectoryOnly)
For Each Filename As String In Directory.GetFiles(Path, Pattern, SO)
File.Delete(Filename)
Next
End Sub
So you could use it for your task like:
DeleteFiles("C:\New Folder")
I would use this code
For Each file As String In IO.Directory.GetFiles("the path")
IO.File.Delete(file)
Next
This deletes everything in the folder but not the folder itself.
This is quick and easy, especially if 1) there's nothing special about the folder, eg permissions, and 2) the folder might contain sub-folders, sub-sub-folders, etc.
Simply delete the original folder and recreate it:
Dim path As String = {your path}
IO.Directory.Delete(path, recursive:=True)
IO.Directory.CreateDirectory(path)
Another option for folders with sub-folders where you wish to keep the (empty) sub-folders, is to use recursion:
Sub EmptyFolder(path As String) As Boolean
Try
For Each dir As String In IO.Directory.GetDirectories(path)
EmptyFolder(dir)
Next dir
For Each file As String In IO.Directory.GetFiles(path)
IO.File.Delete(file)
Next file
Catch
Throw
End Try
End Function
I added a function to get the Active Directory user login, for an Access DB using VBA, but I'm not sure why I don't see my function listed in the Expression Builder
I defined the functions like in this question but I can not see the function in the Expression Builder. I plan to use this function to fill an invisible txtBox on my form and log it into db.
Public Function GetUser(Optional whatpart = "username")
Dim returnthis As String
If whatpart = "username" Then GetUser = Environ("USERNAME"): Exit Function
Set objSysInfo = CreateObject("ADSystemInfo")
Set objUser = GetObject("LDAP://" & objSysInfo.USERNAME)
Select Case whatpart
Case "fullname": returnthis = objUser.FullName
Case "firstname", "givenname": returnthis = objUser.givenName
Case "lastname": returnthis = objUser.LastName
Case Else: returnthis = Environ("USERNAME")
End Select
GetUser = returnthis
End Function
I think you're asking how to have custom functions show up in the Expression Builder? (and therefore unrelated to Active Directory or logins).
It's most likely a simple case of either:
- you haven't saved the module since pasting the functions in, or,
- the functions are not located in a public module.
To make sure they're saved:
1. Close Access completely (all open databases), and then,
2. Re-open the database, and,
3. Open your module (from the "Modules" section of the Navigation Bar:
...and confirm your code is there.
Then try the expression builder again.
If the module is not showing in the Modules section, then your code is not in a public module.
Note that you don't have to use the Expression Builder. I've actually never used it, but I just tried it and once the module with my functions was saved, they showed up under:
Functions → My database name → My module name.
This screenshot shows how my function wasn't listed i the Expression Builder until I saved it, and then how I found it in the Builder:
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.
I am using a SSIS package with an Execute SQL Task connected to Script Task. The values from Execute SQL Task are stored in a variable and in the Script Task I use the following code to give XML file.
Public Sub Main()
If My.Computer.FileSystem.FileExists("C:\SAMPLE.xml") Then
Dts.TaskResult = ScriptResults.Failure
Else
My.Computer.FileSystem.WriteAllText("C:\SAMPLE.xml", Dts.Variables(0).Value.ToString, False)
Dts.TaskResult = ScriptResults.Success
''
End If
End Sub
I don't want to hardcode the path to XML. So I created two new variables FileName and FilePath with package as scope. How do I edit my VB.Net code to actually use these two variables.I tried this but did not work:
Sub Main()
If My.Computer.FileSystem.FileExists(Dts.Variables("FileDest").Value.ToString()) Else
My.Computer.FileSystem.WriteAllText(Dts.Variables("FileDest").Value.ToString(), Dts.Variables(0).Value.ToString, False)Dts.TaskResult = ScriptResults.Success
''
End If
End Sub
Ideally I want to use two variables one for name and one for path but when I tried with a single variable which combines both, it didn't work.
I suspect that part of your problem is using a numeric index into the Variables collection. Once you added the FileDest variable, there's no guarantee that whatever variable was being used to store the Execute SQL Task results is still the zeroeth one in the collection.
Assuming the variable with the Execute SQL Task results is named XmlQueryResults, the following should do the trick:
Public Sub Main()
Dim filePath As String = Dts.Variables("FileDest").Value
Dim xmlToWrite As String = Dts.Variables("XmlQueryResults").Value
If My.Computer.FileSystem.FileExists(filePath) Then
Dts.TaskResult = ScriptResults.Failure
Else
My.Computer.FileSystem.WriteAllText(filePath, xmlToWrite, False)
Dts.TaskResult = ScriptResults.Success
End If
End Sub
(Don't forget to add the FileDest variable to the ReadOnlyVariables in the Script Task Editor script tab.)
I am trying to develop a package in SSIS 2005 and part of my process is to check if a file on the network is empty or not. If it is not empty, I need to pass a status of successful, otherwise, I need to pass a status of unsuccessful. I think I need a script task, but am not sure how to go about it. Any help is appreciated.
Create a connection to the flat file in the Connection Managers panel.
Under the Control flow tab, add a Data Flow Task.
Double click the Data flow task and add a Flat File Source and Row Count item.
In the Row Count properties, create a RowCount variable.
In the Control Flow tab, create control flow connections based on the result of the #RowCount.
There are two ways to do it:
If file empty means size = 0 you can create a Script Task to do the check:
http://msdn.microsoft.com/en-us/library/ms345166.aspx
If My.Computer.FileSystem.FileExists("c:\myfile.txt") Then
Dim myFileInfo As System.IO.FileInfo
myFileInfo = My.Computer.FileSystem.GetFileInfo("c:\myfile.txt")
If myFileInfo.Length = 0 Then
Dts.Variables["Status"].Value = 0
End If
End If
Otherwise, if file empty means no rows (flat file) you can use the a Row Count transformation after you reads the file. You can set a variable from the Row Count using the 'VariableName' property in Row Count editor and use it as a status.
Add a simple Script Task with the following code(C#) should do the trick:
String FilePath = (string)Dts.Variables["User::FilePath"].Value;
var length = new System.IO.FileInfo(FilePath).Length;
if (length == 0)
Dts.TaskResult = (int)ScriptResults.Success;
else
Dts.TaskResult = (int)ScriptResults.Failure;
This option will run a lot quicker than the accepted answer as it doesn't need to read the whole file, if you are cycling through a folder of files and some of them are large, in my case ~800mb, the accepted answer would take ages to run, this solution runs in seconds.
Yes, a Script task will do the job here. Add a using System.IO statement to the top of the script, then something along the lines of the following in the Main method will check the contents of the file.
public void Main()
{
String FilePath = Dts.Variables["User::FilePath"].Value.ToString();
String strContents;
StreamReader sReader;
sReader = File.OpenText(FilePath);
strContents = sReader.ReadToEnd();
sReader.Close();
if (strContents.Length==0)
MessageBox.Show("Empty file");
Dts.TaskResult = (int)ScriptResults.Success;
}
Edit: VB.Net version for 2005...
Public Sub Main()
Dim FilePath As String = Dts.Variables("User::FilePath").Value.ToString()
Dim strContents As String
Dim sReader As StreamReader
sReader = File.OpenText(FilePath)
strContents = sReader.ReadToEnd()
sReader.Close()
If strContents.Length = 0 Then
MessageBox.Show("Empty file")
End If
Dts.TaskResult = ScriptResults.Success
End Sub