Vista: File System Transactions
Windows Vista has several new functions for using transactions when working with files. Here is an example on how to create a transaction, work with some files, and commit it.
Imports System.Runtime.InteropServices
Imports Microsoft.Win32.SafeHandles
Imports System.IO
Module Module1
Public Declare Auto Function CreateTransaction Lib "Ktmw32.dll" (ByVal Attributes As IntPtr, _
ByVal guid As IntPtr, ByVal options As Integer, ByVal isolationlevel As Integer, _
ByVal isolationflags As Integer, ByVal milliseconds As Integer, ByVal description As String) As IntPtr
Public Declare Auto Function RollbackTransaction Lib "Ktmw32.dll" (ByVal handle As IntPtr) As Boolean
Public Declare Auto Function CommitTransaction Lib "Ktmw32.dll" (ByVal handle As IntPtr) As Boolean
Public Declare Auto Function CloseHandle Lib "Kernel32.dll" (ByVal handle As IntPtr) As Boolean
Public Declare Auto Function CreateFileTransacted Lib "Kernel32.dll" (ByVal fileName As String, _
ByVal desiredAccess As Integer, ByVal ShareMode As Integer, ByVal SecurityAttributes As IntPtr, _
ByVal CreationDisposition As Integer, ByVal FlagsAndAttributes As Integer, _
ByVal hTemplateFile As IntPtr, ByVal transaction As IntPtr, _
ByVal miniversion As IntPtr, ByVal extendedOpenInfo As IntPtr) As SafeFileHandle
Public Declare Auto Function DeleteFileTransacted Lib "Kernel32.dll" (ByVal fileName As String, _
ByVal transaction As IntPtr) As Boolean
Private Const GENERIC_READ As Integer = &H80000000
Private Const GENERIC_WRITE As Integer = &H40000000
Private Const CREATE_NEW As Integer = 1
Private Const CREATE_ALWAYS As Integer = 2
Private Const OPEN_EXISTING As Integer = 3
Sub Main()
Using sw As StreamWriter = File.CreateText("test1.txt")
sw.WriteLine("This is the first file")
End Using
Using sw2 As StreamWriter = File.CreateText("test2.txt")
sw2.WriteLine("The other file")
End Using
Console.WriteLine("Before delete")
Console.WriteLine("------------------")
Dim diBefore As New DirectoryInfo(My.Application.Info.DirectoryPath)
For Each fi As FileInfo In diBefore.GetFiles
Console.WriteLine(fi.Name)
Next
Console.WriteLine("------------------")
Console.WriteLine("After transaction delete")
Dim tx As IntPtr = CreateTransaction(IntPtr.Zero, IntPtr.Zero, 0, 0, 0, 0, Nothing)
Dim b As Boolean = DeleteFileTransacted("test1.txt", tx)
Dim sh As SafeFileHandle
sh = CreateFileTransacted("SafeTest.txt", GENERIC_READ Or GENERIC_WRITE, 0, IntPtr.Zero, CREATE_NEW, 0, IntPtr.Zero, tx, IntPtr.Zero, IntPtr.Zero)
Dim fst As New FileStream(sh, FileAccess.Write)
Dim swt As New StreamWriter(fst)
swt.WriteLine("Hello World")
swt.Close()
For Each fi As FileInfo In diBefore.GetFiles
Console.WriteLine(fi.Name)
Next
Console.WriteLine("------------------")
Console.WriteLine("After commit delete")
CommitTransaction(tx)
For Each fi As FileInfo In diBefore.GetFiles
Console.WriteLine(fi.Name)
Next
CloseHandle(tx)
End Sub
End Module