### List Files and Directories on SMB2 Share in C# Source: https://github.com/talaloni/smblibrary/blob/master/ClientExamples.md This snippet shows how to connect to an SMB2 share and list its contents. Similar to the SMB1 example, it uses TreeConnect and CreateFile for directory access, but QueryDirectory is used with FileInformationClass.FileDirectoryInformation for SMB2 specific querying. ```C# ISMBFileStore fileStore = client.TreeConnect("Shared", out status); if (status == NTStatus.STATUS_SUCCESS) { object directoryHandle; FileStatus fileStatus; status = fileStore.CreateFile(out directoryHandle, out fileStatus, String.Empty, AccessMask.GENERIC_READ, FileAttributes.Directory, ShareAccess.Read | ShareAccess.Write, CreateDisposition.FILE_OPEN, CreateOptions.FILE_DIRECTORY_FILE, null); if (status == NTStatus.STATUS_SUCCESS) { List fileList; status = fileStore.QueryDirectory(out fileList, directoryHandle, "*", FileInformationClass.FileDirectoryInformation); status = fileStore.CloseFile(directoryHandle); } } status = fileStore.Disconnect(); ``` -------------------------------- ### Create and Write to File on SMB Share in C# Source: https://github.com/talaloni/smblibrary/blob/master/ClientExamples.md This example shows how to create a new file on an SMB share and write content to it. It handles SMB1 path differences, uses CreateFile with FILE_CREATE disposition, and WriteFile to write a byte array to the newly created file. ```C# ISMBFileStore fileStore = client.TreeConnect("Shared", out status); string filePath = "NewFile.txt"; if (fileStore is SMB1FileStore) { filePath = "\\" + filePath; } objet fileHandle; FileStatus fileStatus; status = fileStore.CreateFile(out fileHandle, out fileStatus, filePath, AccessMask.GENERIC_WRITE | AccessMask.SYNCHRONIZE, FileAttributes.Normal, ShareAccess.None, CreateDisposition.FILE_CREATE, CreateOptions.FILE_NON_DIRECTORY_FILE | CreateOptions.FILE_SYNCHRONOUS_IO_ALERT, null); if (status == NTStatus.STATUS_SUCCESS) { int numberOfBytesWritten; byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes("Hello"); status = fileStore.WriteFile(out numberOfBytesWritten, fileHandle, 0, data); if (status != NTStatus.STATUS_SUCCESS) { throw new Exception("Failed to write to file"); } status = fileStore.CloseFile(fileHandle); } status = fileStore.Disconnect(); ``` -------------------------------- ### List Files and Directories on SMB1 Share in C# Source: https://github.com/talaloni/smblibrary/blob/master/ClientExamples.md This example illustrates how to connect to a specific SMB1 share using TreeConnect and then query its root directory for files and subdirectories. It uses CreateFile to obtain a directory handle and QueryDirectory to list contents, specifically for the SMB1 protocol. ```C# ISMBFileStore fileStore = client.TreeConnect("Shared", out status); if (status == NTStatus.STATUS_SUCCESS) { object directoryHandle; FileStatus fileStatus; status = fileStore.CreateFile(out directoryHandle, out fileStatus, "\\", AccessMask.GENERIC_READ, FileAttributes.Directory, ShareAccess.Read | ShareAccess.Write, CreateDisposition.FILE_OPEN, CreateOptions.FILE_DIRECTORY_FILE, null); if (status == NTStatus.STATUS_SUCCESS) { List fileList2; status = ((SMB1FileStore)fileStore).QueryDirectory(out fileList2, "\\*", FindInformationLevel.SMB_FIND_FILE_DIRECTORY_INFO); status = fileStore.CloseFile(directoryHandle); } } status = fileStore.Disconnect(); ``` -------------------------------- ### Authenticate and List SMB Shares in C# Source: https://github.com/talaloni/smblibrary/blob/master/ClientExamples.md This snippet demonstrates how to connect to an SMB server, authenticate with a username and password, and then list all available shares. It shows the use of SMB1Client (or SMB2Client) for connection, Login for authentication, and ListShares to retrieve share names. ```C# SMB1Client client = new SMB1Client(); // SMB2Client can be used as well bool isConnected = client.Connect(IPAddress.Parse("192.168.1.11"), SMBTransportType.DirectTCPTransport); if (isConnected) { NTStatus status = client.Login(String.Empty, "Username", "Password"); if (status == NTStatus.STATUS_SUCCESS) { List shares = client.ListShares(out status); client.Logoff(); } client.Disconnect(); } ``` -------------------------------- ### SMBServer API Refinements Source: https://github.com/talaloni/smblibrary/blob/master/SMBLibrary/RevisionHistory.txt Refinements to the SMBServer API, centralizing socket parameters within the Start method for cleaner initialization and providing a new method to retrieve detailed information about active SMB sessions. ```APIDOC SMBServer API: Start(socketParameters: object): Initializes and starts the SMB server with specified socket configurations. GetSessionsInformation(): Retrieves detailed information about active SMB sessions. ``` -------------------------------- ### Delete a File using SMB Library in C# Source: https://github.com/talaloni/smblibrary/blob/master/ClientExamples.md This snippet illustrates how to delete an existing file on an SMB share. It first connects to the share and opens the target file with appropriate access rights (GENERIC_WRITE, DELETE, SYNCHRONIZE). It then sets the `DeletePending` flag using `FileDispositionInformation` and closes the file handle, which triggers the actual deletion. The example also includes a conditional adjustment for SMB1 file paths. ```C# ISMBFileStore fileStore = client.TreeConnect("Shared", out status); string filePath = "DeleteMe.txt"; if (fileStore is SMB1FileStore) { filePath = "\\\\" + filePath; } object fileHandle; FileStatus fileStatus; status = fileStore.CreateFile(out fileHandle, out fileStatus, filePath, AccessMask.GENERIC_WRITE | AccessMask.DELETE | AccessMask.SYNCHRONIZE, FileAttributes.Normal, ShareAccess.None, CreateDisposition.FILE_OPEN, CreateOptions.FILE_NON_DIRECTORY_FILE | CreateOptions.FILE_SYNCHRONOUS_IO_ALERT, null); if (status == NTStatus.STATUS_SUCCESS) { FileDispositionInformation fileDispositionInformation = new FileDispositionInformation(); fileDispositionInformation.DeletePending = true; status = fileStore.SetFileInformation(fileHandle, fileDispositionInformation); bool deleteSucceeded = (status == NTStatus.STATUS_SUCCESS); status = fileStore.CloseFile(fileHandle); } status = fileStore.Disconnect(); ``` -------------------------------- ### Create and Write to a File using SMB Library in C# Source: https://github.com/talaloni/smblibrary/blob/master/ClientExamples.md This snippet demonstrates how to create a new file on an SMB share and write content from a local file stream to it. It handles file creation with specific access rights and options, iteratively writes data in chunks based on the client's maximum write size, and ensures proper file closure. It relies on `ISMBFileStore` for SMB interactions and includes error handling for write operations. ```C# FileStream localFileStream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read); object fileHandle; FileStatus fileStatus; status = fileStore.CreateFile(out fileHandle, out fileStatus, remoteFilePath, AccessMask.GENERIC_WRITE | AccessMask.SYNCHRONIZE, FileAttributes.Normal, ShareAccess.None, CreateDisposition.FILE_CREATE, CreateOptions.FILE_NON_DIRECTORY_FILE | CreateOptions.FILE_SYNCHRONOUS_IO_ALERT, null); if (status == NTStatus.STATUS_SUCCESS) { long writeOffset = 0; while (localFileStream.Position < localFileStream.Length) { byte[] buffer = new byte[(int)client.MaxWriteSize]; int bytesRead = localFileStream.Read(buffer, 0, buffer.Length); if (bytesRead < (int)client.MaxWriteSize) { Array.Resize(ref buffer, bytesRead); } int numberOfBytesWritten; status = fileStore.WriteFile(out numberOfBytesWritten, fileHandle, writeOffset, buffer); if (status != NTStatus.STATUS_SUCCESS) { throw new Exception("Failed to write to file"); } writeOffset += bytesRead; } status = fileStore.CloseFile(fileHandle); } status = fileStore.Disconnect(); ``` -------------------------------- ### Write Large File to SMB Share in C# Source: https://github.com/talaloni/smblibrary/blob/master/ClientExamples.md This snippet initiates the process of writing a large local file to an SMB share. It connects to the share and sets up the local and remote file paths, accounting for SMB1 path conventions. Further implementation would involve reading from the local file and writing to the remote file in chunks. ```C# ISMBFileStore fileStore = client.TreeConnect("Shared", out status); if (status != NTStatus.STATUS_SUCCESS) { throw new Exception("Failed to connect to share"); } string localFilePath = @"C:\Image.jpg"; string remoteFilePath = "NewFile.jpg"; if (fileStore is SMB1FileStore) { remoteFilePath = "\\" + remoteFilePath; } ``` -------------------------------- ### Read Large File from SMB Share in C# Source: https://github.com/talaloni/smblibrary/blob/master/ClientExamples.md This code demonstrates how to open and read a large file from an SMB share incrementally until the end of the file is reached. It handles both SMB1 and SMB2 path conventions and uses a loop with ReadFile to stream data into a MemoryStream. ```C# ISMBFileStore fileStore = client.TreeConnect("Shared", out status); object fileHandle; FileStatus fileStatus; string filePath = "IMG_20190109_174446.jpg"; if (fileStore is SMB1FileStore) { filePath = "\\" + filePath; } status = fileStore.CreateFile(out fileHandle, out fileStatus, filePath, AccessMask.GENERIC_READ | AccessMask.SYNCHRONIZE, FileAttributes.Normal, ShareAccess.Read, CreateDisposition.FILE_OPEN, CreateOptions.FILE_NON_DIRECTORY_FILE | CreateOptions.FILE_SYNCHRONOUS_IO_ALERT, null); if (status == NTStatus.STATUS_SUCCESS) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); byte[] data; long bytesRead = 0; while (true) { status = fileStore.ReadFile(out data, fileHandle, bytesRead, (int)client.MaxReadSize); if (status != NTStatus.STATUS_SUCCESS && status != NTStatus.STATUS_END_OF_FILE) { throw new Exception("Failed to read from file"); } if (status == NTStatus.STATUS_END_OF_FILE || data.Length == 0) { break; } bytesRead += data.Length; stream.Write(data, 0, data.Length); } } status = fileStore.CloseFile(fileHandle); status = fileStore.Disconnect(); ``` -------------------------------- ### SMBLibrary File System Interfaces Source: https://github.com/talaloni/smblibrary/blob/master/Readme.md Documentation for the core interfaces, IFileSystem and INTFileStore, that must be implemented by any object or directory structure intended to be shared using SMBLibrary. These interfaces define how SMBLibrary interacts with the underlying data source. ```APIDOC IFileSystem interface: - Purpose: The primary interface that any directory, filesystem, or object must implement to be shared via SMBLibrary. - Requirements: Exposes a directory structure. INTFileStore interface: - Purpose: A lower-level interface compared to IFileSystem. - Usage: Can be used directly for more granular control over file storage operations. ``` -------------------------------- ### File System and Object Store Interfaces API Source: https://github.com/talaloni/smblibrary/blob/master/SMBLibrary/RevisionHistory.txt Introduces DeviceIOControl to the INTFileStore interface for direct device interaction and a SecurityContext class for underlying object store operations. Enhances IFileSystem.OpenFile with a FileOptions parameter and includes bug fixes for NTFileSystemAdapter regarding file deletion and opening behaviors. ```APIDOC INTFileStore Interface: DeviceIOControl(controlCode: int, inBuffer: bytes, outBuffer: bytes): Performs a device I/O control operation. SecurityContext Class: - A new class passed to the underlying object store for security-related operations. IFileSystem Interface: OpenFile(path: str, access: FileAccess, share: FileShare, creationDisposition: CreationDisposition, options: FileOptions): Opens a file with specified options. NTFileSystemAdapter: - Corrected handling of FILE_DELETE_ON_CLOSE. - Corrected handling of FILE_OPEN_IF when the file exists. ``` -------------------------------- ### Windows SMB Port Configuration for SMBLibrary Source: https://github.com/talaloni/smblibrary/blob/master/Readme.md Detailed instructions and methods to configure Windows operating systems to free up or manage SMB ports (139 and 445) for use with SMBLibrary, allowing it to coexist with or replace the built-in Windows File and Printer Sharing service. Includes steps for disabling services, modifying registry keys, and using virtual network adapters. ```APIDOC Method 1: Disable Windows File and Printer Sharing server completely: Windows XP/2003: 1. For every network adapter: Uncheck 'File and Printer Sharing for Microsoft Networks". 2. Navigate to 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NetBT\Parameters' and set 'SMBDeviceEnabled' to '0' (this will free port 445). 3. Reboot. Windows 7/8/2008/2012: Disable the "Server" service (p.s. "TCP\IP NETBIOS Helper" should be enabled). Method 2: Use Windows File Sharing AND SMBLibrary: Windows bind port 139 to the first IP addres of every adapter, while port 445 is bound globally. This means that if you'll disable port 445 (or block it using a firewall), you'll be able to use a different service on port 139 for every IP address. Additional Notes: * To free port 139 for a given adapter, go to 'Internet Protocol (TCP/IP Properties' > Advanced > WINS, and select 'Disable NetBIOS over TCP/IP'. Uncheck 'File and Printer Sharing for Microsoft Networks' to ensure Windows will not answer to SMB traffic on port 445 for this adapter. * It's important to note that disabling NetBIOS over TCP/IP will also disable NetBIOS name service for that adapter (a.k.a. WINS), This service uses UDP port 137. SMBLibrary offers a name service of its own. * You can install a virtual network adapter driver for Windows to be used solely with SMBLibrary: - You can install the 'Microsoft Loopback adapter' and use it for server-only communication with SMBLibrary. Windows 7/8/2008/2012: * It's possible to prevent Windows from using port 445 by removing all of the '\Device\Tcpip_{..}' and '\Device\Tcpip6_{..}' entries from the `Bind' registry key under 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Linkage'. * if you want localhost access from Windows explorer to work as expected, you must specify the IP address that you selected (\\127.0.0.1 or \\localhost will not work as expected), in addition, I have observed that when connecting to the first IP address of a given adapter, Windows will only attempt to connect to port 445. Method 3: Use an IP address that is invisible to Windows File Sharing: Using PCap.Net you can programmatically setup a virtual Network adapter and intercept SMB traffic (similar to how a virtual machine operates), You should use the ARP protocol to notify the network about the new IP address, and then process the incoming SMB traffic using SMBLibrary, good luck! ``` -------------------------------- ### SSPIHelper API Enhancements Source: https://github.com/talaloni/smblibrary/blob/master/SMBLibrary/RevisionHistory.txt Improvements to the Security Support Provider Interface (SSPI) helper, including new methods for retrieving user names and session keys, enhancing security context management. ```APIDOC SSPIHelper: GetUserName(): Retrieves the current user name. GetSessionKey(): Retrieves the session key. ``` -------------------------------- ### GSS Mechanism API Extensibility Source: https://github.com/talaloni/smblibrary/blob/master/SMBLibrary/RevisionHistory.txt Enhancements to GSS-style authentication, allowing for custom IGSSMechanism implementations and improving the extensibility of GSSProvider by marking core methods as virtual. ```APIDOC GSS Authentication API: IGSSMechanism: - Interface for providing custom GSS mechanism implementations. GSSProvider: - Core methods are now virtual for improved extensibility. ``` -------------------------------- ### LoginAPI: ImpersonateLoggedOnUser Method Source: https://github.com/talaloni/smblibrary/blob/master/SMBLibrary/RevisionHistory.txt Addition of a new method to the LoginAPI, enabling the application to impersonate a logged-on user for specific operations, enhancing privilege management. ```APIDOC LoginAPI: ImpersonateLoggedOnUser(): Allows the current process to impersonate a logged-on user. ``` -------------------------------- ### NTLM Authentication Providers API Updates Source: https://github.com/talaloni/smblibrary/blob/master/SMBLibrary/RevisionHistory.txt Comprehensive improvements to NTLM authentication, including session key computation, correct session key return, and proper flag setting for both integrated and independent providers. Addresses bug fixes related to guest status and machine name reading in authentication messages. ```APIDOC NTLM Authentication Providers: IntegratedNTLMAuthenticationProvider: - Ensures correct SessionKey is returned instead of EncryptedRandomSessionKey. - Corrected IsGuest property setting when username does not exist. IndependentNTLMAuthenticationProvider: - Properly sets ChallengeMessage.NegotiateFlags. - Computes and stores SessionKey. - Sets KeyExchange NTLM flag if requested by the client. Common NTLM API: - Added helper method for session key computation. - Fixed MachineName not being read from AuthenticationMessage. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.