public void CreateDirectory(string directoryName)
        {
            object     directoryHandle = null;
            FileStatus fileStatus;

            string currentDir = "";

            foreach (var part in directoryName.Split('/'))
            {
                currentDir = Path.Combine(currentDir, part);
                ThrowOnError(FileStore.CreateFile(
                                 out directoryHandle,
                                 out fileStatus,
                                 currentDir,
                                 AccessMask.GENERIC_WRITE | AccessMask.SYNCHRONIZE,
                                 SMBLibrary.FileAttributes.Directory,
                                 ShareAccess.Delete | ShareAccess.Read | ShareAccess.Write,
                                 CreateDisposition.FILE_OPEN_IF,
                                 CreateOptions.FILE_DIRECTORY_FILE | CreateOptions.FILE_SYNCHRONOUS_IO_ALERT,
                                 null));
                if (fileStatus != FileStatus.FILE_CREATED && fileStatus != FileStatus.FILE_OPENED)
                {
                    throw new IOException($"Cannot create directory {directoryName}");
                }
                CloseFile(directoryHandle);
            }
        }
Exemple #2
0
        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();
        }
Exemple #3
0
        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 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);
        }
        private IDirectoryInfo CreateDirectory(string path, ISMBCredential credential)
        {
            if (!path.IsSharePath())
            {
                return(base.CreateDirectory(path));
            }

            if (!path.TryResolveHostnameFromPath(out var ipAddress))
            {
                throw new SMBException($"Failed to CreateDirectory {path}", new ArgumentException($"Unable to resolve \"{path.Hostname()}\""));
            }

            if (credential == null)
            {
                credential = _credentialProvider.GetSMBCredential(path);
            }

            if (credential == null)
            {
                throw new SMBException($"Failed to CreateDirectory {path}", new InvalidCredentialException($"Unable to find credential in SMBCredentialProvider for path: {path}"));
            }

            if (Exists(path))
            {
                return(_directoryInfoFactory.FromDirectoryName(path));
            }

            ISMBFileStore fileStore = null;
            object        handle    = null;

            try
            {
                var shareName    = path.ShareName();
                var relativePath = path.RelativeSharePath();

                _logger?.LogTrace($"Trying to CreateDirectory {{RelativePath: {relativePath}}} for {{ShareName: {shareName}}}");

                using var connection = SMBConnection.CreateSMBConnection(_smbClientFactory, ipAddress, transport, credential, _maxBufferSize);

                fileStore = connection.SMBClient.TreeConnect(shareName, out var status);

                status.HandleStatus();

                AccessMask        accessMask    = AccessMask.SYNCHRONIZE | AccessMask.MAXIMUM_ALLOWED;
                ShareAccess       shareAccess   = ShareAccess.Read | ShareAccess.Write;
                CreateDisposition disposition   = CreateDisposition.FILE_OPEN_IF;
                CreateOptions     createOptions = CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT | CreateOptions.FILE_DIRECTORY_FILE;

                var stopwatch = new Stopwatch();

                stopwatch.Start();
                do
                {
                    if (status == NTStatus.STATUS_PENDING)
                    {
                        _logger.LogTrace($"STATUS_PENDING while trying to create directory {path}. {stopwatch.Elapsed.TotalSeconds}/{_smbFileSystemSettings.ClientSessionTimeout} seconds elapsed.");
                    }

                    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 && stopwatch.Elapsed.TotalSeconds <= _smbFileSystemSettings.ClientSessionTimeout);

                stopwatch.Stop();

                status.HandleStatus();

                FileStoreUtilities.CloseFile(fileStore, ref handle);

                return(_directoryInfoFactory.FromDirectoryName(path, credential));
            }
            catch (Exception ex)
            {
                throw new SMBException($"Failed to CreateDirectory {path}", ex);
            }
            finally
            {
                FileStoreUtilities.CloseFile(fileStore, ref handle);
            }
        }