Esempio n. 1
0
 public Task <bool> IsDirectoryExists(string directoryPath)
 {
     return(HandleCommonExceptions(() => {
         if (_client.Exists(directoryPath))
         {
             var file = _client.Get(directoryPath);
             return file.IsDirectory;
         }
         return false;
     }));
 }
Esempio n. 2
0
 public Task <bool> IsDirectory(string fileName, DirectoryEnum directoryEnum = DirectoryEnum.Published)
 {
     try
     {
         Connect();
         SftpFile sftpFile = _sftpClient.Get(GetFilePath(fileName, directoryEnum));
         return(Task.FromResult(sftpFile?.IsDirectory ?? false));
     }
     catch
     {
         return(Task.FromResult(false));
     }
 }
Esempio n. 3
0
        public void Test_Sftp_SftpFile_MoveTo()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                string uploadedFileName = Path.GetTempFileName();
                string remoteFileName   = Path.GetRandomFileName();
                string newFileName      = Path.GetRandomFileName();

                this.CreateTestFile(uploadedFileName, 1);

                using (var file = File.OpenRead(uploadedFileName))
                {
                    sftp.UploadFile(file, remoteFileName);
                }

                var sftpFile = sftp.Get(remoteFileName);

                sftpFile.MoveTo(newFileName);

                Assert.AreEqual(newFileName, sftpFile.Name);

                sftp.Disconnect();
            }
        }
        public void Test_Sftp_SftpFile_MoveTo()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                string uploadedFileName = Path.GetTempFileName();
                string remoteFileName = Path.GetRandomFileName();
                string newFileName = Path.GetRandomFileName();

                this.CreateTestFile(uploadedFileName, 1);

                using (var file = File.OpenRead(uploadedFileName))
                {
                    sftp.UploadFile(file, remoteFileName);
                }

                var sftpFile = sftp.Get(remoteFileName);

                sftpFile.MoveTo(newFileName);

                Assert.AreEqual(newFileName, sftpFile.Name);

                sftp.Disconnect();
            }
        }
Esempio n. 5
0
        public Task <FileSpec> GetFileInfoAsync(string path)
        {
            if (String.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            EnsureClientConnected();

            try {
                var file = _client.Get(NormalizePath(path));
                return(Task.FromResult(new FileSpec {
                    Path = file.FullName.TrimStart('/'),
                    Created = file.LastWriteTimeUtc,
                    Modified = file.LastWriteTimeUtc,
                    Size = file.Length
                }));
            } catch (SftpPathNotFoundException ex) {
                if (_logger.IsEnabled(LogLevel.Trace))
                {
                    _logger.LogTrace(ex, "Error trying to getting file info: {Path}", path);
                }

                return(Task.FromResult <FileSpec>(null));
            }
        }
Esempio n. 6
0
        private void UploadFile(SftpClient sftpClient, FileEntry file, string localPath)
        {
            if (verboseMode)
            {
                lock (this)
                {
                    ConsoleOutput($"- {Thread.CurrentThread.ManagedThreadId,2}> Uploading file {file.Name} ({file.Length:N0} bytes)");
                }
            }
            long lastProgress = 0;

            using (var stream = File.OpenRead(Path.Combine(localPath, file.Name)))
            {
                sftpClient.UploadFile(stream, tempUploadDirectory + "/" + file.Name, offset =>
                {
                    lock (this)
                    {
                        uploadedBytes -= lastProgress;
                        uploadedBytes += lastProgress = (long)offset;
                    }
                });
            }
            var sftpFile = sftpClient.Get(tempUploadDirectory + "/" + file.Name);

            sftpFile.LastWriteTimeUtc = file.UtcTime;
            sftpFile.UpdateStatus();
            lock (this)
            {
                uploadedBytes -= lastProgress;
                uploadedBytes += file.Length;
            }
        }
Esempio n. 7
0
        private void Download()
        {
            try
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    using (var stream = new FileStream(LocalDirectory + "/" + listView1.SelectedItems[0].Text, FileMode.Create))
                        using (var oSftp = new SftpClient(ftpPath, ftpUser, ftpPass))
                        {
                            oSftp.Connect();
                            //SftpFileAttributes attributes = Client.GetAttributes(subURL + "/" + listView1.SelectedItems[0].Text);

                            SftpFile file = oSftp.Get(subURL + "/" + listView1.SelectedItems[0].Text);

                            progressBar1.Invoke((MethodInvoker)
                                                delegate
                            {
                                progressBar1.Maximum = (int)file.Attributes.Size;
                            });

                            oSftp.DownloadFile(subURL + "/" + listView1.SelectedItems[0].Text, stream, DownloadProgresBar);
                            oSftp.Disconnect();
                        }
                }));
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Descarga archivo de servidor a un directorio local.
        /// </summary>
        /// <param name="filePath">Ruta de Archivo en servidor remoto.</param>
        /// <param name="destinationPath">Ruta de descarga local.</param>
        /// <returns>Logrado o no logrado.</returns>
        /// <remmarks>No validado.</remmarks>
        public bool Download(string filePath, string destinationPath)
        {
            bool result = false;

            using (SftpClient client = new SftpClient(Host, User, Pass))
            {
                client.Connect();

                if (client.IsConnected)
                {
                    SftpFile file = client.Get(filePath);
                    if (!file.IsDirectory)
                    {
                        string path = $"{destinationPath}/{file.Name}";
                        using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
                        {
                            client.DownloadFile(file.FullName, fs);
                        }

                        result = true;
                    }

                    client.Disconnect();
                }
            }

            return(result);
        }
Esempio n. 9
0
        /// <summary>
        /// Elimina un archivo del servidor SFTP.
        /// </summary>
        /// <param name="filePath">Ruta de Archivo/Directorio dentro del servidor.</param>
        /// <returns>Logrado o no logrado.</returns>
        /// <remarks>No validado.</remarks>
        public bool Delete(string filePath)
        {
            bool result = false;

            using (SftpClient client = new SftpClient(Host, User, Pass))
            {
                client.Connect();

                if (client.IsConnected)
                {
                    SftpFile file = client.Get(filePath);
                    if (file.IsDirectory)
                    {
                        client.DeleteDirectory(file.FullName);
                    }
                    else
                    {
                        client.DeleteFile(file.FullName);
                    }
                    result = true;
                    client.Disconnect();
                }
            }

            return(result);
        }
Esempio n. 10
0
        public static void SftpFileUpload(FTPConfig config)
        {
            ConnectionInfo connectionInfo = new ConnectionInfo(config.IP, config.Port, config.User, new PasswordAuthenticationMethod(config.User, config.Password));

            using (SftpClient sftp = new SftpClient(connectionInfo))
            {
                sftp.Connect();
                sftp.ChangeDirectory(config.Directory);
                FileInfo fi = new FileInfo(config.FilePath);

                using (var uplfileStream = File.OpenRead(config.FilePath))
                {
                    if (config.DeleteIfExists)
                    {
                        try
                        {
                            Renci.SshNet.Sftp.SftpFile file = sftp.Get(fi.Name);

                            if (file.HasValue())
                            {
                                sftp.DeleteFile(file.FullName);
                            }
                        }
                        catch
                        {
                        }
                    }

                    sftp.UploadFile(uplfileStream, fi.Name, true);
                }

                sftp.Disconnect();
            }
        }
Esempio n. 11
0
        public NtStatus GetFileInformation(string fileName, out FileInformation fileInfo, DokanFileInfo info)
        {
            SftpFile file = sftpClient.Get(ToUnixStylePath(fileName));

            fileInfo = new FileInformation()
            {
                FileName       = file.Name,
                Attributes     = FileAttributes.NotContentIndexed,
                CreationTime   = file.LastWriteTime,
                LastAccessTime = file.LastAccessTime,
                LastWriteTime  = file.LastWriteTime,
                Length         = file.Length
            };

            if (file.IsDirectory)
            {
                fileInfo.Attributes |= FileAttributes.Directory;
                fileInfo.Length      = 0;
            }
            else
            {
                fileInfo.Attributes |= FileAttributes.Normal;
            }

            if (fileInfo.FileName.StartsWith("."))
            {
                fileInfo.Attributes |= FileAttributes.Hidden;
            }

            // todo :
            // readonly check

            return(DokanResult.Success);
        }
Esempio n. 12
0
        public async Task <ActionResult> LoadFTPFiles(FTPCredentials credentials, Guid requestId, IEnumerable <string> paths)
        {
            List <Document> uploadedDocuments = new List <Document>();

            using (var sftp = new SftpClient(credentials.Address, credentials.Port, credentials.Login, credentials.Password))
            {
                try
                {
                    sftp.Connect();
                    foreach (var path in paths)
                    {
                        var fileInfo = sftp.Get(path);
                        using (var sSource = sftp.OpenRead(path))
                        {
                            using (var db = new DataContext())
                            {
                                var document = new Document
                                {
                                    CreatedOn = DateTime.UtcNow,
                                    FileName  = fileInfo.Name,
                                    ItemID    = requestId,
                                    Length    = fileInfo.Length,
                                    MimeType  = FileEx.GetMimeTypeByExtension(fileInfo.Name),
                                    Name      = fileInfo.Name,
                                    Viewable  = false,
                                    Kind      = DocumentKind.User
                                };

                                db.Documents.Add(document);
                                uploadedDocuments.Add(document);

                                await db.SaveChangesAsync();

                                var docStream = new DocumentStream(db, document.ID);

                                await sSource.CopyToAsync(docStream);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    return(new HttpStatusCodeResult((int)HttpStatusCode.BadRequest, ex.Message));
                }
                finally
                {
                    if (sftp.IsConnected)
                    {
                        sftp.Disconnect();
                    }
                }
            }

            Response.StatusCode  = (int)HttpStatusCode.OK;
            Response.ContentType = "application/json";

            return(Json(uploadedDocuments.Select(d => new { d.ID, d.FileName, d.MimeType, Size = d.Length }), JsonRequestBehavior.AllowGet));
        }
Esempio n. 13
0
        public void Test_Get_Invalid_Directory()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.Get("/xyz");
            }
        }
Esempio n. 14
0
        public void Test_Get_Invalid_Directory()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.Get("/xyz");
            }
        }
        private string UploadFileProd(string path, string filename)
        {
            try
            {
                User user = GetUser();

                MemoryStream stream = new MemoryStream();

                using (var sftp = new SftpClient(SchemaFtpSiteTest, SchemaUsernameTest, SchemaPasswordTest))
                {
                    sftp.Connect();

                    sftp.DownloadFile(SchemaFtpWorkingDirectoryTest + "/" + path + "/" + filename, stream);
                    sftp.Disconnect();
                }

                using (var sftp = new SftpClient(SchemaFtpSite, user.Username, user.Password))
                {
                    sftp.Connect();

                    string[] subDirs = path.Split('/');

                    string currentDir = SchemaFtpWorkingDirectory;

                    foreach (string subDir in subDirs)
                    {
                        currentDir = currentDir + "/" + subDir;
                        try
                        {
                            SftpFile folder = sftp.Get(currentDir);
                        }
                        catch (SftpPathNotFoundException ex)
                        {
                            sftp.CreateDirectory(currentDir);
                        }
                    }

                    stream.Position = 0;

                    var filePath = currentDir + "/" + filename;
                    sftp.UploadFile(stream, filePath, true);
                    sftp.Disconnect();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw new Exception("Sftp skjema feilet");
            }

            Task.Run(() => LogEntryService.AddLogEntry(new LogEntry {
                ElementId = path + "/" + filename, Operation = Operation.Added, User = ClaimsPrincipal.Current.GetUsername(), Description = "Ftp gml-skjema til prod"
            }));

            return(SchemaRemoteUrl + path + "/" + filename);
        }
Esempio n. 16
0
        public void MoveFile(string sourcePath, string destinationPath)
        {
            using SftpClient sftpClient = CreateSftpClient();

            sftpClient.Connect();

            sftpClient.Get(sourcePath).MoveTo(destinationPath);

            sftpClient.Disconnect();
        }
Esempio n. 17
0
        public HResult GetFileDataCallback(int commandId, string relativePath, ulong byteOffset, uint length, Guid dataStreamId, byte[] contentId, byte[] providerId, uint triggeringProcessId, string triggeringProcessImageFileName)
        {
            if (string.IsNullOrWhiteSpace(relativePath))
            {
                return(HResult.Ok);
            }
            else
            {
                var fullPath = GetFullPath(relativePath);
                if (sftpClient.Exists(fullPath))
                {
                    var  file = sftpClient.Get(fullPath);
                    uint desiredBufferSize = (uint)Math.Min(64 * 1024, file.Length);

                    using (var reader = sftpClient.OpenRead(fullPath)) {
                        using (var writeBuffer = virtualization.CreateWriteBuffer(byteOffset, desiredBufferSize, out var alignedWriteOffset, out var alignedBufferSize)) {
                            while (alignedWriteOffset < (ulong)file.Length)
                            {
                                writeBuffer.Stream.Seek(0, SeekOrigin.Begin);
                                var currentBufferSize = Math.Min(desiredBufferSize, (ulong)file.Length - alignedWriteOffset);
                                var buffer            = new byte[currentBufferSize];
                                reader.Read(buffer, 0, (int)currentBufferSize);
                                writeBuffer.Stream.Write(buffer, 0, (int)currentBufferSize);

                                var hr = virtualization.WriteFileData(dataStreamId, writeBuffer, alignedWriteOffset, (uint)currentBufferSize);
                                if (hr != HResult.Ok)
                                {
                                    return(HResult.InternalError);
                                }

                                alignedWriteOffset += (ulong)currentBufferSize;
                            }
                        }
                    }

                    return(HResult.Ok);
                }
                else
                {
                    return(HResult.FileNotFound);
                }
            }
        }
Esempio n. 18
0
        private static long BackupFile(string root, string remotePath, SftpClient client)
        {
            string name = Path.GetFileName(remotePath);

            // trim rooted paths, including drive letters
            string localPath = Regex.Replace(remotePath, @"^\/[A-Za-z]\:[/\\]", string.Empty).Trim('/', '\\');
            string fileName  = Path.Combine(root, localPath);

            try
            {
                SftpFile file = client.Get(remotePath);
                if (file.IsRegularFile &&
                    (!File.Exists(fileName) || file.LastWriteTimeUtc > File.GetLastWriteTimeUtc(fileName)))
                {
                    string tempFile = fileName + ".__TEMP__";
                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                    using (FileStream stream = File.Create(tempFile))
                    {
                        long prevProgress = 0;
                        client.DownloadFile(remotePath, stream, (progress) =>
                        {
                            Interlocked.Add(ref bytesDownloaded, ((long)progress - prevProgress));
                            prevProgress = (long)progress;
                        });
                    }
                    if (File.Exists(tempFile) && new FileInfo(tempFile).Length == file.Length)
                    {
                        if (File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }
                        File.Move(tempFile, fileName);
                        File.SetLastWriteTimeUtc(fileName, file.LastWriteTimeUtc);
                    }
                }
                else
                {
                    Interlocked.Add(ref bytesSkipped, file.Length);
                }
                return(file.Length);
            }
            catch (SftpPathNotFoundException)
            {
                // OK
            }
            catch (SftpPermissionDeniedException)
            {
                // OK
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}         ", ex.Message);
            }
            return(0);
        }
Esempio n. 19
0
        public void Test_Get_File_Null()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                var file = sftp.Get(null);

                sftp.Disconnect();
            }
        }
Esempio n. 20
0
        public void Test_Get_File_Null()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                var file = sftp.Get(null);

                sftp.Disconnect();
            }
        }
Esempio n. 21
0
        public void Test_Get_Root_Directory()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();
                var directory = sftp.Get("/");

                Assert.AreEqual("/", directory.FullName);
                Assert.IsTrue(directory.IsDirectory);
                Assert.IsFalse(directory.IsRegularFile);
            }
        }
Esempio n. 22
0
        public void Test_Get_Root_Directory()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();
                var directory = sftp.Get("/");

                Assert.AreEqual("/", directory.FullName);
                Assert.IsTrue(directory.IsDirectory);
                Assert.IsFalse(directory.IsRegularFile);
            }
        }
Esempio n. 23
0
        public ItemInfo GetItemInfo(string path)
        {
            if (!string.IsNullOrWhiteSpace(_rootPath))
            {
                path = LexicalPath.Combine(_rootPath, path);
            }

            var info = _client.Get(path);

            return(new ItemInfo {
                Name = info.Name, Size = info.Length, IsDir = info.IsDirectory, Id = info.FullName, LastWriteTime = info.LastWriteTime
            });
        }
Esempio n. 24
0
        /// <summary>
        /// Lists the files.
        /// </summary>
        /// <param name="remotePath">The remote path.</param>
        /// <param name="failRemoteNotExists">if set to <c>true</c> [fail remote not exists].</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public List <IRemoteFileInfo> ListFiles(string remotePath)
        {
            List <IRemoteFileInfo> fileList = new List <IRemoteFileInfo>();

            try
            {
                this.Log(String.Format("Connecting to Host: [{0}].", this.hostName), LogLevel.Minimal);
                using (SftpClient sftp = new SftpClient(this.hostName, this.portNumber, this.userName, this.passWord))
                {
                    sftp.Connect();
                    this.Log(String.Format("Connected to Host: [{0}].", this.hostName), LogLevel.Verbose);

                    if (!sftp.Exists(remotePath))
                    {
                        this.Log(String.Format("Remote Path Does Not Exist: [{0}].", this.hostName), LogLevel.Verbose);
                        if (this.stopOnFailure)
                        {
                            throw new Exception(String.Format("Invalid Path: [{0}]", remotePath));
                        }
                    }
                    else
                    {
                        this.Log(String.Format("Listing Files: [{0}].", remotePath), LogLevel.Minimal);
                        this.Log(String.Format("Getting Attributes: [{0}].", remotePath), LogLevel.Verbose);

                        SftpFile sftpFileInfo = sftp.Get(remotePath);
                        if (sftpFileInfo.IsDirectory)
                        {
                            this.Log(String.Format("Path is a Directory: [{0}].", remotePath), LogLevel.Verbose);
                            IEnumerable <SftpFile> dirList = sftp.ListDirectory(remotePath);
                            foreach (SftpFile sftpFile in dirList)
                            {
                                fileList.Add(this.CreateFileInfo(sftpFile));
                            }
                        }
                        else
                        {
                            this.Log(String.Format("Path is a File: [{0}].", remotePath), LogLevel.Verbose);
                            fileList.Add(this.CreateFileInfo(sftpFileInfo));
                        }
                    }
                }
                this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal);
            }
            catch (Exception ex)
            {
                this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal);
                this.ThrowException("Unable to List: ", ex);
            }
            return(fileList);
        }
Esempio n. 25
0
        ///<summary>Synchronous.  Returns true if a file exists in the passed in filePath</summary>
        private static bool FileExists(SftpClient client, string filePath)
        {
            bool retVal = false;

            try {
                bool hadToConnect = client.ConnectIfNeeded();
                client.Get(filePath);
                client.DisconnectIfNeeded(hadToConnect);
                retVal = true;
            }
            catch (Exception) {
            }
            return(retVal);
        }
Esempio n. 26
0
        private static long BackupFolder(HostEntry host, string root, string path, SftpClient client, StreamWriter log)
        {
            long size = 0;

            foreach (string fileOrFolder in path.Split('|').Select(s => s.Trim()).Where(s => s.Length != 0))
            {
                if (!client.Exists(fileOrFolder))
                {
                    continue;
                }
                SftpFile file;
                try
                {
                    file = client.Get(fileOrFolder);
                }
                catch (SftpPathNotFoundException)
                {
                    continue;
                }
                catch (Exception ex)
                {
                    log.WriteLine("Error backing up folder {0}: {1}", fileOrFolder, ex);
                    continue;
                }
                if (file.IsRegularFile)
                {
                    Interlocked.Add(ref size, BackupFile(root, file.FullName, client));
                }
                else
                {
                    try
                    {
                        SftpFile[] files = client.ListDirectory(fileOrFolder).Where(f => f.IsRegularFile || (f.IsDirectory && !f.Name.StartsWith("."))).ToArray();
                        Parallel.ForEach(files.Where(f => f.IsRegularFile && (host.IgnoreRegex == null || !host.IgnoreRegex.IsMatch(f.FullName))), parallelOptions, (_file) =>
                        {
                            Interlocked.Add(ref size, BackupFile(root, _file.FullName, client));
                        });
                        Parallel.ForEach(files.Where(f => f.IsDirectory && (host.IgnoreRegex == null || !host.IgnoreRegex.IsMatch(f.FullName))), parallelOptions2, (folder) =>
                        {
                            Interlocked.Add(ref size, BackupFolder(host, root, folder.FullName, client, log));
                        });
                    }
                    catch (Exception ex)
                    {
                        log.WriteLine("Failed to backup file or folder {0}, error: {1}", fileOrFolder, ex.Message);
                    }
                }
            }
            return(size);
        }
Esempio n. 27
0
        private IEnumerable <Tuple <string, string> > GetRemoteListing(string remotePath, string localPath, bool recursive)
        {
            if (string.IsNullOrWhiteSpace(remotePath))
            {
                throw new ArgumentNullException(nameof(remotePath));
            }
            if (string.IsNullOrWhiteSpace(localPath))
            {
                throw new ArgumentNullException(nameof(localPath));
            }

            string initialWorkingDirectory = _sftpClient.WorkingDirectory;

            _sftpClient.ChangeDirectory(remotePath);

            List <Tuple <string, string> > listing = new List <Tuple <string, string> >();
            SftpFile currentDirectory    = _sftpClient.Get(_sftpClient.WorkingDirectory);
            IEnumerable <SftpFile> items = _sftpClient.ListDirectory(currentDirectory.FullName);
            string nextLocalPath         = Path.Combine(localPath, currentDirectory.Name);

            foreach (SftpFile file in items.Where(i => i.IsRegularFile))
            {
                listing.Add(new Tuple <string, string>(Path.Combine(nextLocalPath, file.Name), file.FullName));
            }

            if (recursive)
            {
                foreach (SftpFile directory in items.Where(i => i.IsDirectory && i.Name != "." && i.Name != ".."))
                {
                    listing.AddRange(GetRemoteListing(directory.FullName, nextLocalPath, recursive));
                }
            }

            _sftpClient.ChangeDirectory(initialWorkingDirectory);

            return(listing);
        }
Esempio n. 28
0
 public Boolean MyFTPFileHasData(string remoteFile)
 {
     using (var sftp = new SftpClient(host, Port, user, pass))
     {
         Boolean  isData = false;
         String[] dList  = new string[] { };
         sftp.Connect();
         if (sftp.Get(remoteFile).Length > 500)
         {
             isData = true;
         }
         sftp.Disconnect();
         return(isData);
     }
 }
Esempio n. 29
0
 //ファイルサイズを取得
 public long GetFileSize(string From_File, bool IsErrorLogMode = false)
 {
     if (!IsConnected)
     {
         return(0);
     }
     else if (!SFTP_Server.IsConnected)
     {
         SFTP_Server.Connect();
     }
     try
     {
         SftpFile GetFileInfo = SFTP_Server.Get(From_File);
         return(GetFileInfo.Attributes.Size);
     }
     catch (Exception e)
     {
         if (IsErrorLogMode)
         {
             Sub_Code.Error_Log_Write(e.Message);
         }
         return(0);
     }
 }
Esempio n. 30
0
        public void Test_Get_File()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.UploadFile(new MemoryStream(), "abc.txt");

                var file = sftp.Get("abc.txt");

                Assert.AreEqual("/home/tester/abc.txt", file.FullName);
                Assert.IsTrue(file.IsRegularFile);
                Assert.IsFalse(file.IsDirectory);
            }
        }
Esempio n. 31
0
        public override async Task <IFile> GetFileAsync(string path, CancellationToken cancellationToken = default)
        {
            path = PrependRootPath(path);

            try
            {
                var file = await Task.Run(() => client.Get(path), cancellationToken);

                if (file.IsDirectory)
                {
                    throw new FileNotFoundException(path, Prefix);
                }

                return(ModelFactory.CreateFile(file));
            }
            catch (SftpPathNotFoundException)
            {
                throw new FileNotFoundException(path, Prefix);
            }
            catch (Exception exception)
            {
                throw Exception(exception);
            }
        }
Esempio n. 32
0
        public void Test_Get_International_File()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.UploadFile(new MemoryStream(), "test-üöä-");

                var file = sftp.Get("test-üöä-");

                Assert.AreEqual("/home/tester/test-üöä-", file.FullName);
                Assert.IsTrue(file.IsRegularFile);
                Assert.IsFalse(file.IsDirectory);
            }
        }
Esempio n. 33
0
        public FDCDirectoryInfo GetDirectoryInfo(string server, int port, string directory)
        {
            directory = AdjustPath(server, directory);
            SftpClient client = null;

            try
            {
                client = OpenSftpClient(server, port);

                try
                {
                    SftpFile a = client.Get(directory);

                    if (a.IsDirectory)
                    {
                        return new FDCDirectoryInfo {
                                   CreationTimeUtc = a.LastWriteTimeUtc, LastAccessTimeUtc = a.LastAccessTimeUtc, LastWriteTimeUtc = a.LastWriteTimeUtc
                        }
                    }
                    ;
                }
                catch
                {
                }
                finally
                {
                    RecycleClient(client);
                    client = null;
                }
            }
            catch (Exception ex)
            {
                try
                {
                    client.Disconnect();
                }
                catch { }
                try
                {
                    client.Dispose();
                }
                catch { }

                STEM.Sys.EventLog.WriteEntry("Authentication.GetDirectoryInfo", ex.ToString(), STEM.Sys.EventLog.EventLogEntryType.Error);
            }

            return(null);
        }
Esempio n. 34
0
        public FDCFileInfo GetFileInfo(string server, int port, string file)
        {
            file = AdjustPath(server, file);
            SftpClient client = null;

            try
            {
                client = OpenSftpClient(server, port);

                try
                {
                    SftpFile a = client.Get(file);

                    if (a.IsRegularFile)
                    {
                        return new FDCFileInfo {
                                   CreationTimeUtc = a.LastWriteTimeUtc, LastAccessTimeUtc = a.LastAccessTimeUtc, LastWriteTimeUtc = a.LastWriteTimeUtc, Size = a.Attributes.Size
                        }
                    }
                    ;
                }
                catch
                {
                }
                finally
                {
                    RecycleClient(client);
                    client = null;
                }
            }
            catch (Exception ex)
            {
                try
                {
                    client.Disconnect();
                }
                catch { }
                try
                {
                    client.Dispose();
                }
                catch { }

                STEM.Sys.EventLog.WriteEntry("Authentication.GetFileInfo", ex.ToString(), STEM.Sys.EventLog.EventLogEntryType.Error);
            }

            return(null);
        }
Esempio n. 35
0
        /// <summary>
        /// 保存到联贷平台SFTP
        /// </summary>
        public bool SaveToGFSftp(string remotePath, Stream fileStream, string fileName)
        {
            var isSuccess = false;

            try
            {
                using (var client = new SftpClient(gfFtpIp, int.Parse(gfFtpPort), gfFtpAccount, gfFtpPassword)) //创建连接对象
                {
                    client.Connect();                                                                           //连接

                    if (!client.Exists(remotePath))
                    {
                        var paths = remotePath.Split('/');

                        if (paths.Length > 1)
                        {
                            var path = "";
                            foreach (var p in paths)
                            {
                                path += "/" + p;
                                if (!client.Exists(path))
                                {
                                    client.CreateDirectory(path);
                                }
                            }
                        }
                    }

                    client.ChangeDirectory(remotePath);      //切换目录

                    client.UploadFile(fileStream, fileName); //上传文件

                    var stpFile = client.Get(fileName);
                    if (stpFile.IsRegularFile)
                    {
                        isSuccess = true;
                    }

                    client.Disconnect();
                }
            }
            catch (Exception ex)
            {
                AppUtility.Engine.LogWriter.Write($"联贷平台SFTP上传{remotePath}/{fileName}文件错误{ex.ToString()}");
            }
            return(isSuccess);
        }
Esempio n. 36
0
 public void GetTest()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
     string path = string.Empty; // TODO: Initialize to an appropriate value
     SftpFile expected = null; // TODO: Initialize to an appropriate value
     SftpFile actual;
     actual = target.Get(path);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }