I have been asked to create a console application which polls an active Directory. (C.\Temp\Input)
When a file comes in with (filename).SUCCESS, filename is retrieve in order to run a SQL query. So
IF fileextension = SUCCESS
Runs SQL Query using filename to change a value in the SQL Table.
Moves Original file to c:\temp\Input\Processed
Any help or hints would be much appreciated.
UPDATED:
Hi, With a few looks at various sites iv come up with the below. Forgetting the SQL for now, im only after the Filename and the moving of files but im getting an IO Exception that the file is already in use:
Imports System.IO
Imports System.String
Module Module1
Dim fileName As String = "C:\temp\Input\NR12345.success"
Dim pathname As String = "C:\temp\Input\"
Dim result As String
Dim sourceDir As String = "C:\temp\Input\"
Dim processedDir As String = "C:\temp\Input\Processed\"
Dim fList As String() = Directory.GetFiles(sourceDir, "*.success")
Sub Main()
result = Path.GetFileName(fileName)
Console.WriteLine("GetFileName('{0}') returns '{1}'", fileName, result)
result = Path.GetFileName(pathname)
Console.WriteLine("GetFileName('{0}') returns '{1}'", pathname, result)
Call MySub()
End Sub
Sub MySub()
'Move Files
For Each f As String In fList
'Remove path from the file name.
Dim fName As String = f.Substring(sourceDir.Length = 0)
Dim sourceFile = Path.Combine(sourceDir, fName)
Dim processedFileDir = Path.Combine(processedDir, fName)
' Use the Path.Combine method to safely append the file name to the path.
' Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(processedDir, fName), True)
'File.Copy(sourceFile, processedFileDir)
Next f
End Sub
End Module
I've used this before:
The FileWather Class
Really useful for polling directories for changes in structure and file details etc.
You can then use this to get an extension of a file and, if it meets your criteria, perform some actions.
These links come with examples so enjoy!!
Sub MySub()
'Move Files
For Each f As String In fList
Dim fInfo As FileInfo = New FileInfo(f)
Dim fName As String = fInfo.Name
Dim processedFileDir = Path.Combine(processedDir, fName)
' Use the Path.Combine method to safely append the file name to the path.
' Will overwrite if the destination file already exists.
File.Copy(fInfo.FullName, processedFileDir, True)
Next f
End Sub
Related
i'm trying to get vb to read the most recent modified pdf file in a specific folder and display the pdf file on my vb form. I only able to create a simple pdf display on my vb form and i'm stuck at this. Can anyone help?
Unable to find solution to my problem.
Dim testFile As System.IO.FileInfo
Dim fileName As String
Dim folderPath As String
Dim fullPath As String
testFile = My.Computer.FileSystem.GetFileInfo("C:\Users\example.pdf")
folderPath = testFile.DirectoryName
fileName = testFile.Name
fullPath = My.Computer.FileSystem.CombinePath(folderPath, fileName)
AxAcroPDF1.src = fullPath
my vb form should display the PDF based on the most recent modified file.
You can use the IO.DirectoryInfo class to get every IO.FileInfo in a directory while specifically targeting PDF files, then use LINQ to order them by their LastWriteTime, and then get the last file from the collection:
Dim folder As IO.DirectoryInfo = New IO.DirectoryInfo("my folder path here")
Dim lastModifiedPdf As IO.FileInfo = folder.GetFiles("*.pdf").OrderBy(Function(f) f.LastWriteTime).LastOrDefault()
If lastModifiedPdf IsNot Nothing Then
'....
End If
You need to call two sets of functions to achieve this.
A. Directory.GetFiles - this will list all the files in a directory, and it has options to provide a search pattern and also look in sub-folders.
B. File.GetLastWriteTime - this will return the last modified time of the file you pass to it.
You can put these functions together like:
Private Function GetLatestModifiedFileName(searchFolder As String) As String
Dim retVal = "<empty>"
Dim filesInDirectory() = Directory.GetFiles(searchFolder)
Dim latestModifiedtime As DateTime = DateTime.MinValue
For Each fileInDirectory As String In filesInDirectory
Dim currentFileModifiedTime As DateTime = File.GetLastWriteTime(fileInDirectory)
If (currentFileModifiedTime > latestModifiedtime) Then
retVal = fileInDirectory
latestModifiedtime = currentFileModifiedTime
End If
Next
Debug.Print("File: '{0}' was last modified on: '{1}'", retVal, latestModifiedtime)
Return retVal
End Function
and ultimately call this function using:
Dim lastModifiedFileName = GetLatestModifiedFileName("D:\Documents\")
The variable lastModifiedFileName will contain the full path to the file that has the latest modified date/time.
The following script task in SSIS connects to a FTP server and is supposed to look for a file until it exists, then copy that file to a local folder. It's doing everything correctly but instead of looking for the specific file, it's copying ALL files.
I've pieced the script together from various forums as I'm not a VB writer. It appears the fileName.Contains is being ignored.
Any help would be great. Thanks!
' Microsoft SQL Server Integration Services Script Task
' Write scripts using Microsoft Visual Basic 2008.
' The ScriptMain is the entry point class of the script.
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
<Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute>
<System.CLSCompliantAttribute(False)>
Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End Enum
Public Sub Main()
System.Threading.Thread.Sleep(50000)
Dim VarCol As Variables = Nothing
Dts.VariableDispenser.LockForWrite("User::FileFound")
Dts.VariableDispenser.LockForWrite("User::FileName")
Dts.VariableDispenser.GetVariables(VarCol)
Try
'Create the connection to the ftp server
Dim cm As ConnectionManager = Dts.Connections.Add("FTP")
Dim strFolders As String()
Dim strFiles As String()
Dim fileCount As Int32
fileCount = 0
Dim fileName As String
'Set the properties like username & password
cm.Properties("ServerName").SetValue(cm, "ftp.testing.com")
cm.Properties("ServerUserName").SetValue(cm, "username") 'user name
cm.Properties("ServerPassword").SetValue(cm, "password") 'password
Dim ftp As FtpClientConnection = New FtpClientConnection(cm.AcquireConnection(Nothing))
'Connects to the ftp server
ftp.Connect()
ftp.SetWorkingDirectory("/testing")
ftp.GetListing(strFolders, strFiles)
For Each fileName In strFiles
If fileName.Contains("test.xml") Then 'file has such word in its name
ftp.ReceiveFiles(strFiles, "\\FTPSERVER\c$\FTP FILES\testing", True, False) 'download file if found
fileCount = fileCount + 1
VarCol("User::FileFound").Value = fileName
VarCol("User::FileFound").Value = True
Else
VarCol("User::FileFound").Value = False
End If
Next
ftp.Close()
VarCol.Unlock()
Catch ex As Exception
Dts.TaskResult = ScriptResults.Failure
End Try
Dts.TaskResult = ScriptResults.Success
End Sub
End Class
Ok, I am not up on VB code so the syntax is most likely not right but the logic here should do what you need (you will just have to update to match VB syntax). I put comments in the code to show what I am doing and also a problem with returning one of the file names in your current logic (I did not fix that I just pointed it out).
//declare string array to pass to your FTP call for only matching fiels
Dim FileNameListMatching as String()
For Each fileName In strFiles
If fileName.Contains("test.xml") Then 'file has such word in its name
// then if the file name matches in the if above, add that filename at the fileCount location into the string array
FileNameListMatching(fileCount) = fileName
fileCount = fileCount + 1
// this will have a problem here though because you are populating a variable with the fileName, but if there is more then 1 fileName found in your logic, it will overwrite it with only the most recent file name. The True value is fine, because you dont care if there is more then 1 for that, but the file name returned will only give you the most recent file name if more then 1
VarCol("User::FileFound").Value = fileName
VarCol("User::FileFound").Value = True
Else
VarCol("User::FileFound").Value = False
End If
Next
-- then if filecount is > 0 then call your FTP to copy files
if fileCount > 0
ftp.ReceiveFiles(FileNameListMatching, "\\FTPSERVER\c$\FTP FILES\testing", True, False) 'download file if found
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.
I am trying to get my application to check for folders in the folderbrowserdialogs selectedpath and then get those files, but it doesn't work I have tried both listed ways below. The second way gives me an error: (Expression is of type char which is not a collection type)
For Each folder In FileBrowserDialog.SelectedPath
Dim counter As _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
counter = My.Computer.FileSystem.GetFiles(folder)
Label1.Text = counter.Count.ToString
Next
For Each folder In FileBrowserDialog.SelectedPath
Dim counter As _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
For Each foundfile In folder
counter = My.Computer.FileSystem.GetFiles(foundfile)
Label1.Text = counter.Count.ToString
Next
Any help is appreciated.
FolderBrowserDialog1.SelectedPath will return the path the user selected in the dialog. You still need to write code to go get the files. There may not be a need to get the folders and then files in them. Net has ways to do that for you:
FolderBrowserDialog1.ShowDialog()
Dim myPath As String = FolderBrowserDialog1.SelectedPath
' get all files for a folder
Dim files = Directory.GetFiles(myPath)
' get all files for all sub folders
Dim files = Directory.GetFiles(myPath, "*.*",
System.IO.SearchOption.AllDirectories)
' get certain file types for folder and subs
Dim files = Directory.GetFiles(myPath, "*.jpg",
System.IO.SearchOption.AllDirectories)
You also are not going to be able to simply assign the results to a ReadOnlyCollection like that, because they are ReadOnly. The collection needs to be created/instanced with the complete list:
Dim counter As new ReadOnlyCollection(Of String)(files)
How I can Paste from Clipboard a file to my path? I work in VB .NET. I got filename from clipboard but don't know how to extract file from cliboard and save it to my folder.
Dim data As IDataObject = Clipboard.GetDataObject()
If data.GetDataPresent(DataFormats.FileDrop) Then
Dim files As String() = data.GetData(DataFormats.FileDrop)
End If
Can anybody help me?
Thanks in advance!
You can use the Path class to both isolate the file name and create the path of the new file to use in a file copy operation:
Dim data As IDataObject = Clipboard.GetDataObject
If data.GetDataPresent(DataFormats.FileDrop) Then
For Each s As String In data.GetData(DataFormats.FileDrop)
Dim newFile As String = Path.Combine("c:\mynewpath", Path.GetFileName(s))
File.Copy(s, newFile)
Next
End If
Example needs error checking.
You can also get the full path to the file as follows:
Dim objeto As IDataObject = Clipboard.GetDataObject
For Each data As String In objeto.GetData(DataFormats.FileDrop)
...
Dim newFile As String = Path.GetFullPath(data.ToString)
...
Next