public override bool Exists(string path) { if (!path.IsSharePath()) { return(base.Exists(path)); } try { if (!path.TryResolveHostnameFromPath(out var ipAddress)) { throw new ArgumentException($"Unable to resolve \"{path.Hostname()}\""); } NTStatus status = NTStatus.STATUS_SUCCESS; var credential = _credentialProvider.GetSMBCredential(path); using (var connection = SMBConnection.CreateSMBConnection(_smbClientFactory, ipAddress, transport, credential, _maxBufferSize)) { var shareName = path.ShareName(); var directoryPath = _fileSystem.Path.GetDirectoryName(path); var fileName = _fileSystem.Path.GetFileName(path); ISMBFileStore fileStore = connection.SMBClient.TreeConnect(shareName, out status); status.HandleStatus(); status = fileStore.CreateFile(out object handle, out FileStatus fileStatus, directoryPath, AccessMask.GENERIC_READ, 0, ShareAccess.Read, CreateDisposition.FILE_OPEN, CreateOptions.FILE_DIRECTORY_FILE, null); status.HandleStatus(); fileStore.QueryDirectory(out List <QueryDirectoryFileInformation> queryDirectoryFileInformation, handle, string.IsNullOrEmpty(fileName) ? "*" : fileName, FileInformationClass.FileDirectoryInformation); foreach (var file in queryDirectoryFileInformation) { if (file.FileInformationClass == FileInformationClass.FileDirectoryInformation) { FileDirectoryInformation fileDirectoryInformation = (FileDirectoryInformation)file; if (fileDirectoryInformation.FileName == fileName) { fileStore.CloseFile(handle); return(true); } } } fileStore.CloseFile(handle); } return(false); } catch { return(false); } }
public IEnumerable <FileDirectoryInformation> EnumerateFileEntries(string path, string searchPattern, SearchOption searchOption) { if (path.StartsWith("/")) { path = path.Substring(1); } ThrowOnError(FileStore.CreateFile( out var directoryHandle, out var fileStatus, path, AccessMask.GENERIC_READ, SMBLibrary.FileAttributes.Directory, ShareAccess.Read | ShareAccess.Write, CreateDisposition.FILE_OPEN, CreateOptions.FILE_DIRECTORY_FILE, null)); List <QueryDirectoryFileInformation> fileList; var status = FileStore.QueryDirectory(out fileList, directoryHandle, searchPattern, FileInformationClass.FileDirectoryInformation); var result = fileList .OfType <FileDirectoryInformation>() .Where(f => f.FileName != "." && f.FileName != "..") .Select(f => { f.FileName = Path.Combine(path, f.FileName); return(f); }); if (searchOption == SearchOption.AllDirectories) { FileStore.QueryDirectory(out var dirList, directoryHandle, "*", FileInformationClass.FileDirectoryInformation); var dirsToEnter = dirList.OfType <FileDirectoryInformation>() .Where(f => f.FileName != "." && f.FileName != "..") .Select(f => { f.FileName = Path.Combine(path, f.FileName); return(f); }); var lresult = new List <FileDirectoryInformation>(result); foreach (var dir in dirsToEnter.Where(r => r.FileAttributes.HasFlag(SMBLibrary.FileAttributes.Directory)).ToArray()) { lresult.AddRange(EnumerateFileEntries(dir.FileName, searchPattern, searchOption)); } ThrowOnError(FileStore.CloseFile(directoryHandle)); return(lresult); } ThrowOnError(FileStore.CloseFile(directoryHandle)); return(result); }
public List <SMBItem> RetrieveItems(string path) { NTStatus status = fileStore.CreateFile(out object directoryHandle, out FileStatus fileStatus, path, AccessMask.GENERIC_READ, FileAttributes.Directory, ShareAccess.Read | ShareAccess.Write, CreateDisposition.FILE_OPEN, CreateOptions.FILE_DIRECTORY_FILE, null); if (status != NTStatus.STATUS_SUCCESS) { throw new IOException($"Could not fetch files and directories: {status}"); } fileStore.QueryDirectory(out var fileList, directoryHandle, "*", FileInformationClass.FileDirectoryInformation); fileStore.CloseFile(directoryHandle); return(fileList.Cast <FileDirectoryInformation>() .Where(fdi => fdi.FileName.Trim('.').Length > 0) .Select(fdi => new SMBItem(fdi, path)) .ToList()); }
public static void CloseFile(ISMBFileStore fileStore, ref object fileHandle) { if (fileStore == null || fileHandle == null) { return; } fileStore.CloseFile(fileHandle); fileHandle = null; }
public void readSmbFile() { SMB1Client client = new SMB1Client(); // SMB2Client can be used as well bool isConnected = client.Connect(IPAddress.Parse("192.168.10.200"), SMBTransportType.DirectTCPTransport); if (isConnected) { NTStatus status = client.Login(String.Empty, "jing.luo", "ximai_2016"); ISMBFileStore fileStore = client.TreeConnect("software", out status); object fileHandle; FileStatus fileStatus; string filePath = "EXCEL在财务管理中的高级应用.pdf"; if (fileStore is SMB1FileStore) { filePath = @"\\" + filePath; } status = fileStore.CreateFile(out fileHandle, out fileStatus, filePath, AccessMask.GENERIC_READ | AccessMask.SYNCHRONIZE, (SMBLibrary.FileAttributes)System.IO.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(); } //if (status == NTStatus.STATUS_SUCCESS) //{ // List<string> shares = client.ListShares(out status); // client.Logoff(); //} //client.Disconnect(); }
internal void Delete(string path, ISMBCredential credential) { if (!path.IsSharePath()) { base.Delete(path); return; } if (!path.TryResolveHostnameFromPath(out var ipAddress)) { throw new ArgumentException($"Unable to resolve \"{path.Hostname()}\""); } NTStatus status = NTStatus.STATUS_SUCCESS; if (credential == null) { credential = _credentialProvider.GetSMBCredential(path); } if (EnumerateFileSystemEntries(path).Count() > 0) { throw new IOException("Cannot delete directory. Directory is not empty."); } using (var connection = SMBConnection.CreateSMBConnection(_smbClientFactory, ipAddress, transport, credential, _maxBufferSize)) { var shareName = path.ShareName(); var relativePath = path.RelativeSharePath(); ISMBFileStore fileStore = connection.SMBClient.TreeConnect(shareName, out status); status.HandleStatus(); int attempts = 0; int allowedRetrys = 3; object handle; do { attempts++; status = fileStore.CreateFile(out handle, out FileStatus fileStatus, relativePath, AccessMask.DELETE, 0, ShareAccess.Delete, CreateDisposition.FILE_OPEN, CreateOptions.FILE_DELETE_ON_CLOSE, null); }while (status == NTStatus.STATUS_PENDING && attempts < allowedRetrys); status.HandleStatus(); // This is the correct delete command, but it doesn't work for some reason. You have to use FILE_DELETE_ON_CLOSE // fileStore.SetFileInformation(handle, new FileDispositionInformation()); fileStore.CloseFile(handle); } }
internal IFileInfo FromFileName(string path, ISMBCredential credential) { if (!path.IsSharePath()) { return(null); } if (!path.TryResolveHostnameFromPath(out var ipAddress)) { throw new ArgumentException($"Unable to resolve \"{path.Hostname()}\""); } NTStatus status = NTStatus.STATUS_SUCCESS; if (credential == null) { credential = _credentialProvider.GetSMBCredential(path); } if (credential == null) { throw new Exception($"Unable to find credential for path: {path}"); } using var connection = SMBConnection.CreateSMBConnection(_smbClientFactory, ipAddress, transport, credential, _maxBufferSize); var shareName = path.ShareName(); var relativePath = path.RelativeSharePath(); ISMBFileStore fileStore = connection.SMBClient.TreeConnect(shareName, out status); status.HandleStatus(); status = fileStore.CreateFile(out object handle, out FileStatus fileStatus, relativePath, AccessMask.GENERIC_READ, 0, ShareAccess.Read, CreateDisposition.FILE_OPEN, CreateOptions.FILE_NON_DIRECTORY_FILE, null); status.HandleStatus(); status = fileStore.GetFileInformation(out FileInformation fileBasicInfo, handle, FileInformationClass.FileBasicInformation); status.HandleStatus(); status = fileStore.GetFileInformation(out FileInformation fileStandardInfo, handle, FileInformationClass.FileStandardInformation); status.HandleStatus(); fileStore.CloseFile(handle); return(new SMBFileInfo(path, _fileSystem, (FileBasicInformation)fileBasicInfo, (FileStandardInformation)fileStandardInfo, credential)); }
public override void Delete(string path) { if (!path.IsSharePath()) { base.Delete(path); return; } if (!path.TryResolveHostnameFromPath(out var ipAddress)) { throw new ArgumentException($"Unable to resolve \"{path.Hostname()}\""); } NTStatus status = NTStatus.STATUS_SUCCESS; var credential = _credentialProvider.GetSMBCredential(path); using (var connection = SMBConnection.CreateSMBConnection(_smbClientFactory, ipAddress, transport, credential, _maxBufferSize)) { var shareName = path.ShareName(); var relativePath = path.RelativeSharePath(); var directoryPath = _fileSystem.Path.GetDirectoryName(relativePath); ISMBFileStore fileStore = connection.SMBClient.TreeConnect(shareName, out status); status.HandleStatus(); int attempts = 0; int allowedRetrys = 3; object handle; do { attempts++; status = fileStore.CreateFile(out handle, out FileStatus fileStatus, relativePath, AccessMask.DELETE, 0, ShareAccess.Read, CreateDisposition.FILE_OPEN, CreateOptions.FILE_DELETE_ON_CLOSE, null); }while (status == NTStatus.STATUS_PENDING && attempts < allowedRetrys); status.HandleStatus(); // There should be a seperate option to delete, but it doesn't seem to exsist in the library we are using, so this should work for now. Really hacky though. fileStore.CloseFile(handle); } }
protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { if (pipeHandle != null && NamedPipeShare != null) { NamedPipeShare.CloseFile(pipeHandle); } if (NamedPipeShare != null) { NamedPipeShare.Disconnect(); } } disposedValue = true; } }
private IEnumerable <string> EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption, ISMBCredential credential) { if (!path.IsSharePath()) { return(base.EnumerateFileSystemEntries(path, searchPattern, searchOption)); } if (!path.TryResolveHostnameFromPath(out var ipAddress)) { throw new ArgumentException($"Unable to resolve \"{path.Hostname()}\""); } NTStatus status = NTStatus.STATUS_SUCCESS; if (credential == null) { credential = _credentialProvider.GetSMBCredential(path); } using (var connection = SMBConnection.CreateSMBConnection(_smbClientFactory, ipAddress, transport, credential, _maxBufferSize)) { var shareName = path.ShareName(); var relativePath = path.RelativeSharePath(); ISMBFileStore fileStore = connection.SMBClient.TreeConnect(shareName, out status); status.HandleStatus(); status = fileStore.CreateFile(out object handle, out FileStatus fileStatus, relativePath, AccessMask.GENERIC_READ, 0, ShareAccess.Read, CreateDisposition.FILE_OPEN, CreateOptions.FILE_DIRECTORY_FILE, null); status.HandleStatus(); fileStore.QueryDirectory(out List <QueryDirectoryFileInformation> queryDirectoryFileInformation, handle, searchPattern, FileInformationClass.FileDirectoryInformation); List <string> files = new List <string>(); foreach (var file in queryDirectoryFileInformation) { if (file.FileInformationClass == FileInformationClass.FileDirectoryInformation) { FileDirectoryInformation fileDirectoryInformation = (FileDirectoryInformation)file; if (fileDirectoryInformation.FileName == "." || fileDirectoryInformation.FileName == ".." || fileDirectoryInformation.FileName == ".DS_Store") { continue; } if (fileDirectoryInformation.FileAttributes.HasFlag(SMBLibrary.FileAttributes.Directory)) { if (searchOption == SearchOption.AllDirectories) { files.AddRange(EnumerateFileSystemEntries(_fileSystem.Path.Combine(path, fileDirectoryInformation.FileName), searchPattern, searchOption, credential)); } } files.Add(_fileSystem.Path.Combine(path, fileDirectoryInformation.FileName)); } } fileStore.CloseFile(handle); return(files); } }
private IDirectoryInfo CreateDirectory(string path, ISMBCredential credential) { if (!path.IsSharePath()) { return(base.CreateDirectory(path)); } if (!path.TryResolveHostnameFromPath(out var ipAddress)) { throw new ArgumentException($"Unable to resolve \"{path.Hostname()}\""); } NTStatus status = NTStatus.STATUS_SUCCESS; AccessMask accessMask = AccessMask.MAXIMUM_ALLOWED; ShareAccess shareAccess = ShareAccess.Read; CreateDisposition disposition = CreateDisposition.FILE_OPEN_IF; CreateOptions createOptions = CreateOptions.FILE_DIRECTORY_FILE; if (credential == null) { credential = _credentialProvider.GetSMBCredential(path); } if (credential == null) { throw new Exception($"Unable to find credential for path: {path}"); } using var connection = SMBConnection.CreateSMBConnection(_smbClientFactory, ipAddress, transport, credential, _maxBufferSize); var shareName = path.ShareName(); var relativePath = path.RelativeSharePath(); ISMBFileStore fileStore = connection.SMBClient.TreeConnect(shareName, out status); status.HandleStatus(); int attempts = 0; int allowedRetrys = 3; object handle; do { attempts++; status = fileStore.CreateFile(out handle, out FileStatus fileStatus, relativePath, accessMask, 0, shareAccess, disposition, createOptions, null); if (status == NTStatus.STATUS_OBJECT_PATH_NOT_FOUND) { CreateDirectory(path.GetParentPath(), credential); status = fileStore.CreateFile(out handle, out fileStatus, relativePath, accessMask, 0, shareAccess, disposition, createOptions, null); } }while (status == NTStatus.STATUS_PENDING && attempts < allowedRetrys); status.HandleStatus(); fileStore.CloseFile(handle); return(_directoryInfoFactory.FromDirectoryName(path, credential)); }
public void Delete(string path, bool recursive, ISMBCredential credential) { if (!path.IsSharePath()) { base.Delete(path, recursive); return; } if (recursive) { if (!path.TryResolveHostnameFromPath(out var ipAddress)) { throw new ArgumentException($"Unable to resolve \"{path.Hostname()}\""); } NTStatus status = NTStatus.STATUS_SUCCESS; if (credential == null) { credential = _credentialProvider.GetSMBCredential(path); } using (var connection = SMBConnection.CreateSMBConnection(_smbClientFactory, ipAddress, transport, credential, _maxBufferSize)) { var shareName = path.ShareName(); var relativePath = path.RelativeSharePath(); ISMBFileStore fileStore = connection.SMBClient.TreeConnect(shareName, out status); status.HandleStatus(); int attempts = 0; int allowedRetrys = 3; object handle; do { attempts++; status = fileStore.CreateFile(out handle, out FileStatus fileStatus, relativePath, AccessMask.GENERIC_READ, 0, ShareAccess.Delete, CreateDisposition.FILE_OPEN, CreateOptions.FILE_DIRECTORY_FILE, null); }while (status == NTStatus.STATUS_PENDING && attempts < allowedRetrys); status.HandleStatus(); fileStore.QueryDirectory(out List <QueryDirectoryFileInformation> queryDirectoryFileInformation, handle, "*", FileInformationClass.FileDirectoryInformation); foreach (var file in queryDirectoryFileInformation) { if (file.FileInformationClass == FileInformationClass.FileDirectoryInformation) { FileDirectoryInformation fileDirectoryInformation = (FileDirectoryInformation)file; if (fileDirectoryInformation.FileName == "." || fileDirectoryInformation.FileName == ".." || fileDirectoryInformation.FileName == ".DS_Store") { continue; } else if (fileDirectoryInformation.FileAttributes.HasFlag(SMBLibrary.FileAttributes.Directory)) { Delete(_fileSystem.Path.Combine(path, fileDirectoryInformation.FileName), recursive, credential); } _fileSystem.File.Delete(_fileSystem.Path.Combine(path, fileDirectoryInformation.FileName)); } } fileStore.CloseFile(handle); Delete(path, credential); } } else { Delete(path); } }
protected override void Dispose(bool disposing) { _fileStore.CloseFile(_fileHandle); _connection.Dispose(); base.Dispose(disposing); }
void IDisposable.Dispose() { fileStore.CloseFile(fileHandle); }
public static Microsoft.SharePoint.Client.File GetBigSharePointFile(string fileurl, string filename, SMBCredential SMBCredential, SMB2Client client, NTStatus nts, ISMBFileStore fileStore, List list, ClientContext cc, DocumentModel doc, List <Metadata> fields) { Microsoft.SharePoint.Client.File uploadFile = null; ClientResult <long> bytesUploaded = null; //SMBLibrary.NTStatus actionStatus; FileCreationInformation newFile = new FileCreationInformation(); NTStatus status = nts; object handle; FileStatus fileStatus; string tmpfile = Path.GetTempFileName(); status = fileStore.CreateFile(out handle, out fileStatus, fileurl, AccessMask.GENERIC_READ, 0, ShareAccess.Read, CreateDisposition.FILE_OPEN, CreateOptions.FILE_NON_DIRECTORY_FILE, null); if (status != NTStatus.STATUS_SUCCESS) { Console.WriteLine(status); return(null); } else { string uniqueFileName = String.Empty; int blockSize = 8000000; // 8 MB long fileSize; Guid uploadId = Guid.NewGuid(); byte[] buf; var fs = new FileStream(tmpfile, FileMode.OpenOrCreate); var bw = new BinaryWriter(fs); int bufsz = 64 * 1000; int i = 0; do { status = fileStore.ReadFile(out buf, handle, i * bufsz, bufsz); if (status == NTStatus.STATUS_SUCCESS) { int n = buf.GetLength(0); bw.Write(buf, 0, n); if (n < bufsz) { break; } i++; } }while (status != NTStatus.STATUS_END_OF_FILE && i < 1000); if (status == NTStatus.STATUS_SUCCESS) { fileStore.CloseFile(handle); bw.Flush(); fs.Close(); //fs = System.IO.File.OpenRead(tmpfile); //byte[] fileBytes = new byte[fs.Length]; //fs.Read(fileBytes, 0, fileBytes.Length); try { fs = System.IO.File.Open(tmpfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); fileSize = fs.Length; uniqueFileName = Path.GetFileName(fs.Name); using (BinaryReader br = new BinaryReader(fs)) { byte[] buffer = new byte[blockSize]; byte[] lastBuffer = null; long fileoffset = 0; long totalBytesRead = 0; int bytesRead; bool first = true; bool last = false; while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0) { totalBytesRead = totalBytesRead + bytesRead; if (totalBytesRead >= fileSize) { last = true; lastBuffer = new byte[bytesRead]; Array.Copy(buffer, 0, lastBuffer, 0, bytesRead); } if (first) { using (MemoryStream contentStream = new MemoryStream()) { newFile.ContentStream = contentStream; newFile.Url = uniqueFileName; newFile.Overwrite = true; if (doc.foldername == null) { uploadFile = list.RootFolder.Files.Add(newFile); } /*else * { * string foldername = doc.foldername; * string sitecontent = doc.sitecontent; * * //Folder folder = list.RootFolder.Folders.GetByUrl(foldername); * * Folder folder = GetFolder(cc, list, foldername); * if (folder == null){ * if(doc.taxFields != null){ * folder = CreateDocumentSetWithTaxonomy(cc, list, sitecontent, foldername, doc.fields, fields, doc.taxFields); * } * else * { * folder = CreateFolder(cc, list, sitecontent, foldername, doc.fields, fields); * } * * } * }*/ using (MemoryStream s = new MemoryStream(buffer)) { bytesUploaded = uploadFile.StartUpload(uploadId, s); cc.ExecuteQuery(); fileoffset = bytesUploaded.Value; } first = false; } } else { uploadFile = cc.Web.GetFileByServerRelativeUrl(list.RootFolder.ServerRelativeUrl + Path.AltDirectorySeparatorChar + uniqueFileName); if (last) { using (MemoryStream s = new MemoryStream(lastBuffer)) { uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s); cc.ExecuteQuery(); } } else { using (MemoryStream s = new MemoryStream(buffer)) { bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s); cc.ExecuteQuery(); fileoffset = bytesUploaded.Value; } } } } } } finally { System.IO.File.Delete(tmpfile); if (fs != null) { fs.Dispose(); } } } else { System.IO.File.Delete(tmpfile); return(null); } return(uploadFile); } }
public static FileCreationInformation GetFileCreationInformation(string fileurl, string filename, SMBCredential SMBCredential, SMB2Client client, NTStatus nts, ISMBFileStore fileStore) { //SMBLibrary.NTStatus actionStatus; FileCreationInformation newFile = new FileCreationInformation(); NTStatus status = nts; object handle; FileStatus fileStatus; //string path = fileurl; //string path = "Dokument/ARKIV/RUNSAL/23_02_2011/sz001!.PDF"; string tmpfile = Path.GetTempFileName(); status = fileStore.CreateFile(out handle, out fileStatus, fileurl, AccessMask.GENERIC_READ, 0, ShareAccess.Read, CreateDisposition.FILE_OPEN, CreateOptions.FILE_NON_DIRECTORY_FILE, null); if (status != NTStatus.STATUS_SUCCESS) { Console.WriteLine(status); return(null); } else { byte[] buf; var fs = new FileStream(tmpfile, FileMode.OpenOrCreate); var bw = new BinaryWriter(fs); int bufsz = 64 * 1000; int i = 0; do { status = fileStore.ReadFile(out buf, handle, i * bufsz, bufsz); if (status == NTStatus.STATUS_SUCCESS) { int n = buf.GetLength(0); bw.Write(buf, 0, n); if (n < bufsz) { break; } i++; } }while (status != NTStatus.STATUS_END_OF_FILE && i < 1000); if (status == NTStatus.STATUS_SUCCESS) { fileStore.CloseFile(handle); bw.Flush(); fs.Close(); fs = System.IO.File.OpenRead(tmpfile); //byte[] fileBytes = new byte[fs.Length]; //fs.Read(fileBytes, 0, fileBytes.Length); newFile.Overwrite = true; newFile.ContentStream = fs; //newFile.Content = fileBytes; newFile.Url = filename; } else { System.IO.File.Delete(tmpfile); return(null); } System.IO.File.Delete(tmpfile); } return(newFile); }