I have been trying to figure out how to zip an Excel .Xlsm file with no luck. The following code creates the zip file, but I can't figure out how to send the .xlsm file to it. Any help is appreciated!
Dim zipPath As String = RegScoringWorkbookName.Replace(".xlsm", ".zip") 'create zip file from .xlsm file
Try
If File.Exists(zipPath) Then
My.Computer.FileSystem.DeleteFile(zipPath, FileIO.UIOption.OnlyErrorDialogs,
FileIO.RecycleOption.DeletePermanently)
End If
Dim FilePath As String = RegScoringWorkbookName 'path of .xlsm file
Using FileStream = New FileStream(zipPath, FileMode.CreateNew)
Using archive = New ZipArchive(FileStream, ZipArchiveMode.Create, True)
Dim zipArchiveEntry = archive.CreateEntry(GetFileName(FilePath), CompressionLevel.Optimal)
Using zipStream = zipArchiveEntry.Open()
' zipStream.WriteAsync()
zipStream.Close()
End Using
End Using
End Using
Catch ex As Exception
End Try
I will just quote MSDN code here, since there is this exact example.
http://msdn.microsoft.com/de-de/library/vstudio/system.io.compression.ziparchive
Imports System.IO
Imports System.IO.Compression
Module Module1
Sub Main()
Dim zipPath As String = "c:\users\exampleuser\end.zip"
Dim extractPath As String = "c:\users\exampleuser\extract"
Dim newFile As String = "c:\users\exampleuser\NewFile.txt"
Using archive As ZipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Create) 'Changed this to create from MSDN
archive.CreateEntryFromFile(newFile, "NewEntry.txt", CompressionLevel.Fastest)
End Using
End Sub
End Module
It should be pretty self explanatory. There is no need to use a filestream at this point, as there is a premade method to zip an existing file, CreateEntryFromFile.
Related
How can i open .exe file from the multiple folders in single click using vb.net or any other way?
tried using process.start method but it's not working properly and found error can't find path.
Example:
For Each Dir As String In Directory.GetDirectories(Application.StartupPath)
Process.Start(Dir & "\" & "*.exe")
Next
This will try to run all EXE files in the folder "myPath" and subfolders
Imports System.IO
Module Module1
Sub Main()
Dim pattern As String
pattern = "*.EXE"
Dim myPath As String
myPath = "your Path" ' Adjust to your needs
Dim exeLst As IEnumerable(Of String)
exeLst = Directory.EnumerateFiles(myPath, pattern, SearchOption.AllDirectories)
Dim sngFile As String
For Each sngFile In exeLst
Process.Start(sngFile)
Next
End Sub
End Module
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 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 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
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()