How to paste a file from Clipboard to specific path - vb.net

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

Related

How to get most recent modified date pdf file and display on VB from?

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.

Convert multiple .xls files to .xlsx in ssis

I have a folder that receives multiple excel files in .xls format. I need to change the format type to .xlsx in order to load the excel data into SQLvia SSIS. I know how to rename the file using "File System Task" but that works for a specific file. but my file contains a file # and date as well that needs to stay same as source file, I only want the file type to change and the file move to a processed folder. Can anyone help me?
Source Path: C:\Documents\TestFolder
Source File: TestSegRpt_0001_2017_02_22.xls
Destination Path: C:\Documents\TestFolderProcessed
Destination File: TestSegRpt_0001_2017_02_22.xlsx
Hoping i understood your problem correctly.
I think below link will help.
https://answers.microsoft.com/en-us/msoffice/forum/msoffice_excel-mso_other/batch-convert-xls-to-xlsx/1d9b3d78-daf0-4014-8fb2-930aca6493b0
You have to add a Script Task, loop over files, and use a function like the following to create precessed directory and convert files (code in Vb.net):
Public Sub ConvertXlsToXlsx(ByVal strpath as string)
Dim strDirectory as string = System.IO.Path.GetDirectoryName(strpath) & "Processed"
If Not System.IO.Directory.Exists(strDirectory) Then System.IO.Directory.CreateDirectory(strDirectory)
Dim xl As New Microsoft.Office.Interop.Excel.Application
Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
xlWorkBook = xl.Workbooks.Open(strpath)
xlBook.SaveAs(strDirectory & "\" & System.IO.Path.GetFilename(strpath) & "x")
xl.Application.Workbooks.Close()
xl.Application.Quit()
End Sub
Your code will look like:
Public Sub Main
Dim strFolder as string = Dts.Variables.Item("FolderPath").Value
Dim strXlsFiles() as string = IO.Directory.GetFiles(strFolder,"*.xlsx",SearchOption.TopDirectoryOnly)
For each strFile as String in strXlsFiles
If strFile.EndsWith("xlsx") The Continue For
ConvertXlsToXlsx(strFile)
Next
End Sub
Reference:
https://social.msdn.microsoft.com/Forums/office/en-US/a73f846c-91ee-4dad-bd7b-c04d418d0561/convert-xls-into-xlsx?forum=exceldev

VB.net Read File Name from Dir to Run SQL Query

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

How to get the file name of a file in VB?

I make a search program for searching a list of files in a computer and then copy the file into a store folder. The file name could be "*11*2.txt" As long as the program find this pattern, it should copy to the store folder. The problem is that I don't know the exactly name of the file before the search and I don't want to rename the file, I don't know how to save the file. Please help
I use the following to find the file, which does its work
Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
Dim To_Path As String
To_Path = Form1.TextBox5.Text
For Each foundFile As String In My.Computer.FileSystem.GetFiles(sDir, FileIO.SearchOption.SearchAllSubDirectories, FileName)
Copy2Local(foundFile, To_Path)
Next
End Sub
Here is the current version of the Copy2Local (Note: it is not working right)
Public Sub Copy2Local(ByVal Copy_From_Path As String, ByVal Copy_To_Path As String)
' Specify the directories you want to manipulate.
Try
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
' Copy the file.
File.Copy(Copy_From_Path, Copy_To_Path)
Catch
End Try
End Sub
First, you should check if ToPath is a valid directory since it's coming from a TextBox:
Dim isValidDir = Directory.Exists(ToPath)
Second, you can use Path.Combine to create a path from separate (sub)directories or file-names:
Dim copyToDir = Path.GetDirectoryName(Copy_To_Path)
Dim file = Path.GetFileName(Copy_From_Path)
Dim newPath = Path.Combine(copyToDir, file)
http://msdn.microsoft.com/en-us/library/system.io.path.aspx
(disclaimer: typed from a mobile)
To answer your question: You can get the file name with Path.GetFileName. Example:
Dim fileName As String = Path.GetFileName(foundFile)
However, there's a bunch of other things wrong with your code:
Here,
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
you are overwriting your source file. This does not seem like a good idea. ;-)
And here,
Try
...
Catch
' Do Nothing
End Try
You are throwing away exceptions that would help you find and diagnose problems. Don't do that. It makes debugging a nightmare.
In vb.net, I'm using the following code to find the filename
Textbox1.Text = New FileInfo(OpenFileDialog.FileName).Name
this code work fine with open file dialog box

Visual Basic label

If i have information (for example a name) in a label on a form in Visual Basic, how do I save this information in a .txt file?
Thanks
You can use the classes in the System.IO namespace. Look at File and its methods.
This example uses one overload of WriteAllText:
File.WriteAllText("Path To Text File.txt", myLabel.Text)
It will write the text value of the myLabel control to the specifies text file.
You use StreamWriter to do that. Here's an example:
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()
If you want to know how to read from txt files, here's a example code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
MsgBox(fileReader)
You can use file system object for ealier versions of Visual basic.
' VBScript
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine(label.caption)
MyFile.Close
http://msdn.microsoft.com/en-us/library/z9ty6h50(VS.85).aspx
or
Sub Create_File()
Dim fso, txtfile
Set fso = CreateObject("Scripting.FileSystemObject")
Set txtfile = fso.CreateTextFile("c:\testfile.txt", True)
txtfile.Write (lable.caption) ' Write a line.
' Write a line with a newline character.
txtfile.WriteLine("Testing 1, 2, 3.")
' Write three newline characters to the file.
txtfile.WriteBlankLines(3)
txtfile.Close
End Sub
http://msdn.microsoft.com/en-us/library/aa263346(VS.60).aspx
Put it directly into the place you needed
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("filename.txt", True)
file.WriteLine("Your Text Here~")
file.Close()