예제 #1
0
 public SftpMkDirRequest(uint protocolVersion, uint requestId, string path, Encoding encoding, SftpFileAttributes attributes, Action<SftpStatusResponse> statusAction)
     : base(protocolVersion, requestId, statusAction)
 {
     this.Path = path;
     this.Encoding = encoding;
     this.Attributes = attributes;
 }
예제 #2
0
        public SftpOpenRequest(uint requestId, string fileName, Flags flags, SftpFileAttributes attributes, Action<SftpHandleResponse> handleAction, Action<SftpStatusResponse> statusAction)
            : base(requestId, statusAction)
        {
            this.Filename = fileName;
            this.Flags = flags;
            this.Attributes = attributes;

            this.SetAction(handleAction);
        }
예제 #3
0
        public SftpOpenRequest(uint protocolVersion, uint requestId, string fileName, Encoding encoding, Flags flags, SftpFileAttributes attributes, Action<SftpHandleResponse> handleAction, Action<SftpStatusResponse> statusAction)
            : base(protocolVersion, requestId, statusAction)
        {
            this.Filename = fileName;
            this.Flags = flags;
            this.Attributes = attributes;
            this.Encoding = encoding;

            this.SetAction(handleAction);
        }
예제 #4
0
        public void LastWriteTimeTest()
        {
            SftpSession        sftpSession = null;                                            // TODO: Initialize to an appropriate value
            string             fullName    = string.Empty;                                    // TODO: Initialize to an appropriate value
            SftpFileAttributes attributes  = null;                                            // TODO: Initialize to an appropriate value
            SftpFile           target      = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
            DateTime           expected    = new DateTime();                                  // TODO: Initialize to an appropriate value
            DateTime           actual;

            target.LastWriteTime = expected;
            actual = target.LastWriteTime;
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
예제 #5
0
        public void GroupCanReadTest()
        {
            SftpSession        sftpSession = null;                                            // TODO: Initialize to an appropriate value
            string             fullName    = string.Empty;                                    // TODO: Initialize to an appropriate value
            SftpFileAttributes attributes  = null;                                            // TODO: Initialize to an appropriate value
            SftpFile           target      = new SftpFile(sftpSession, fullName, attributes); // TODO: Initialize to an appropriate value
            bool expected = false;                                                            // TODO: Initialize to an appropriate value
            bool actual;

            target.GroupCanRead = expected;
            actual = target.GroupCanRead;
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
예제 #6
0
        public bool IsExist(string absolutePath)
        {
            bool IsExist = false;

            try
            {
                SftpFileAttributes fileAttr = Sftp.GetAttributes(absolutePath);
                IsExist = true;
            }
            catch
            {
                IsExist = false;
            }

            return(IsExist);
        }
예제 #7
0
        ///// <summary>
        ///// download online maps
        ///// </summary>
        ///// <param name="_selectedCityName"></param>
        public void DownloadOnlineMaps(string _selectedCityName)
        {
            string cityName            = _selectedCityName + ".csv";
            var    deviceDocumentsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments);
            string cityPath            = deviceDocumentsPath.AbsolutePath + "/OHDM_MAP/" + cityName;



            using (SftpClient sftp = new SftpClient(@serverName, login, password))
            {
                try
                {
                    sftp.Connect();
                    using (Stream fileStream = File.OpenWrite(cityPath))
                    {
                        SftpFileAttributes attributes = sftp.GetAttributes(directory + cityName);                             //recover the file size
                        progress.Max = (int)attributes.Size;                                                                  // Set progress bar maximum on foreground thread
                        sftp.DownloadFile(directory + cityName, fileStream, downloadProgressBar);
                        fileStream.Close();
                    }
                    sftp.Disconnect();
                }
                catch (Exception er)
                {
                    Console.WriteLine("Error " + er);
                    if (!sftp.IsConnected)
                    {
                        RunOnUiThread(() =>
                        {
                            //enable/disable  widgets
                            spinner.Enabled        = true;
                            switchSlider.Enabled   = true;
                            datePickerText.Enabled = false;

                            displayMessage(5);   // Display message if the connection to the FTP server Failed
                        });
                    }
                }
            }

            processCsv(csvLocalPath);
            mapView = FindViewById <MapView>(Resource.Id.mapView);
            MapView.RegisterLicense(LICENSE, this);
            mapView.SetZoom(18f, 0f);
        }
예제 #8
0
        public bool DirectoryExists(string server, int port, string directory)
        {
            directory = AdjustPath(server, directory);
            SftpClient client = null;

            try
            {
                client = OpenSftpClient(server, port);

                try
                {
                    SftpFileAttributes a = client.GetAttributes(directory);

                    if (a.IsDirectory)
                    {
                        return(true);
                    }
                }
                catch
                {
                }
                finally
                {
                    RecycleClient(client);
                    client = null;
                }
            }
            catch (Exception ex)
            {
                try
                {
                    client.Disconnect();
                }
                catch { }
                try
                {
                    client.Dispose();
                }
                catch { }

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

            return(false);
        }
        protected void Arrange()
        {
            _random          = new Random();
            _path            = _random.Next().ToString(CultureInfo.InvariantCulture);
            _handle          = new[] { (byte)_random.Next(byte.MinValue, byte.MaxValue) };
            _fileAttributes  = SftpFileAttributes.Empty;
            _bufferSize      = (uint)_random.Next(1, 1000);
            _readBufferSize  = (uint)_random.Next(0, 1000);
            _writeBufferSize = (uint)_random.Next(500, 1000);
            _data            = new byte[(_writeBufferSize * 2) + 15];
            _random.NextBytes(_data);
            _offset = _random.Next(1, 5);
            // to get multiple SSH_FXP_WRITE messages (and verify the offset is updated correctly), we make sure
            // the number of bytes to write is at least two times the write buffer size; we write a few extra bytes to
            // ensure the buffer is not empty after the writes so we can verify whether Length, Dispose and Flush
            // flush the buffer
            _count = ((int)_writeBufferSize * 2) + _random.Next(1, 5);

            _expectedWrittenByteCount  = (2 * _writeBufferSize);
            _expectedBufferedByteCount = (int)(_count - _expectedWrittenByteCount);
            _expectedBufferedBytes     = _data.Take(_offset + (int)_expectedWrittenByteCount, _expectedBufferedByteCount);

            _sftpSessionMock = new Mock <ISftpSession>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.Truncate, true))
            .Returns(_handle);
            _sftpSessionMock.InSequence(_sequence).Setup(p => p.RequestFStat(_handle)).Returns(_fileAttributes);
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.CalculateOptimalReadLength(_bufferSize))
            .Returns(_readBufferSize);
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle))
            .Returns(_writeBufferSize);
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.IsOpen)
            .Returns(true);
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.RequestWrite(_handle, 0, _data, _offset, (int)_writeBufferSize, It.IsAny <AutoResetEvent>(), null));
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.RequestWrite(_handle, _writeBufferSize, _data, _offset + (int)_writeBufferSize, (int)_writeBufferSize, It.IsAny <AutoResetEvent>(), null));

            _sftpFileStream = new SftpFileStream(_sftpSessionMock.Object, _path, FileMode.Create, FileAccess.Write, (int)_bufferSize);
        }
예제 #10
0
        private SftpFileInfo CreateDirectoryRecursively(string path)
        {
            path = NormalizePath(path);
            string current = "";

            if (path[0] == PathSeparator)
            {
                path = path.Substring(1);
            }

            while (!string.IsNullOrEmpty(path))
            {
                int p = path.IndexOf(PathSeparator);
                current += PathSeparator;
                if (p >= 0)
                {
                    current += path.Substring(0, p);
                    path     = path.Substring(p + 1);
                }
                else
                {
                    current += path;
                    path     = "";
                }

                try
                {
                    SftpFileAttributes attrs = Client.GetAttributes(current);
                    if (!attrs.IsDirectory)
                    {
                        return(null);
                    }
                }
                catch (SftpPathNotFoundException)
                {
                    Client.CreateDirectory(current);
                }
            }

            var file = Client.Get(current);

            return(new SftpFileInfo(this, file));
        }
예제 #11
0
        private bool ShouldDownloadNewFile(FileSystemInfo existingFileInfo, SftpFileAttributes newFileInfo)
        {
            try
            {
                // If the file on the FTP site is not newer than our current file, the file won't be downloaded
                if (newFileInfo.LastWriteTime < existingFileInfo.LastWriteTime)
                {
                    _logger.Information("File already exists and does not need to be re-downloaded.", existingFileInfo, newFileInfo);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Unable to compare the existing file to the file to download.");
                return(false);
            }

            return(true);
        }
예제 #12
0
        protected override void SetupData()
        {
            base.SetupData();

            _random          = new Random();
            _path            = _random.Next().ToString();
            _fileMode        = FileMode.Append;
            _fileAccess      = FileAccess.Write;
            _bufferSize      = _random.Next(5, 1000);
            _readBufferSize  = (uint)_random.Next(5, 1000);
            _writeBufferSize = (uint)_random.Next(5, 1000);
            _handle          = GenerateRandom(_random.Next(1, 10), _random);
            _fileAttributes  = new SftpFileAttributesBuilder().WithLastAccessTime(DateTime.Now.AddSeconds(_random.Next()))
                               .WithLastWriteTime(DateTime.Now.AddSeconds(_random.Next()))
                               .WithSize(_random.Next())
                               .WithUserId(_random.Next())
                               .WithGroupId(_random.Next())
                               .WithPermissions((uint)_random.Next())
                               .Build();
        }
예제 #13
0
        public NtStatus SetFileTime(string fileName, DateTime?creationTime, DateTime?lastAccessTime, DateTime?lastWriteTime, DokanFileInfo info)
        {
            fileName = ToUnixStylePath(fileName);

            SftpFileAttributes attr = sftpClient.GetAttributes(fileName);

            if (lastAccessTime != null)
            {
                attr.LastAccessTime = lastAccessTime.Value;
            }

            if (lastWriteTime != null)
            {
                attr.LastWriteTime = lastWriteTime.Value;
            }

            sftpClient.SetAttributes(fileName, attr);

            return(DokanResult.Success);
        }
예제 #14
0
 public void DownloadFile(string remoteFileName, string localFileName, Action <double> downloadAction = null)
 {
     using (FileStream stream = File.Open(localFileName, FileMode.OpenOrCreate))
     {
         try
         {
             using (SftpClient client = new SftpClient(_ConnectionInfo))
             {
                 client.Connect();
                 SftpFileAttributes attributes = client.GetAttributes(remoteFileName);
                 client.DownloadFile(remoteFileName, stream, delegate(ulong i)
                 {
                     downloadAction?.Invoke(i / (double)attributes.Size);
                 });
             }
         }
         catch (Exception)
         {
         }
     }
 }
예제 #15
0
 protected override void SetupMocks()
 {
     _sequence = new MockSequence();
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write, false))
     .Returns(_handle);
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.CalculateOptimalReadLength(_bufferSize))
     .Returns(_readBufferSize);
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle))
     .Returns(_writeBufferSize);
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.IsOpen)
     .Returns(true);
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.RequestRead(_handle, 0, _readBufferSize))
     .Returns(_actualReadBytes);
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.IsOpen)
     .Returns(true);
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.IsOpen)
     .Returns(true);
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.RequestWrite(_handle, (uint)_readBytes.Length, It.IsAny <byte[]>(), 0, _writeBytes.Length, It.IsAny <AutoResetEvent>(), null))
     .Callback <byte[], ulong, byte[], int, int, AutoResetEvent, Action <SftpStatusResponse> >((handle, serverOffset, data, offset, length, wait, writeCompleted)
                                                                                               =>
     {
         _actualWrittenBytes = data.Take(offset, length);
         wait.Set();
     });
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.RequestFStat(_handle, false))
     .Returns(_fileAttributes);
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.RequestFSetStat(_handle, _fileAttributes))
     .Callback <byte[], SftpFileAttributes>((bytes, attributes) => _newFileAttributes = attributes.Clone());
 }
        public void LengthShouldFlushBufferAndReturnSizeOfFile()
        {
            var lengthFileAttributes = new SftpFileAttributes(DateTime.Now, DateTime.Now, _random.Next(), _random.Next(),
                                                              _random.Next(), (uint)_random.Next(0, int.MaxValue), null);

            byte[] actualFlushedData = null;

            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.IsOpen)
            .Returns(true);
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.RequestWrite(_handle, _expectedWrittenByteCount, It.IsAny <byte[]>(), 0, _expectedBufferedByteCount, It.IsAny <AutoResetEvent>(), null))
            .Callback <byte[], ulong, byte[], int, int, AutoResetEvent, Action <SftpStatusResponse> >((handle, serverFileOffset, data, offset, length, wait, writeCompleted) => actualFlushedData = data.Take(offset, length));
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.RequestFStat(_handle))
            .Returns(lengthFileAttributes);

            Assert.AreEqual(lengthFileAttributes.Size, _sftpFileStream.Length);
            Assert.IsTrue(actualFlushedData.IsEqualTo(_expectedBufferedBytes));

            _sftpSessionMock.Verify(p => p.RequestWrite(_handle, _expectedWrittenByteCount, It.IsAny <byte[]>(), 0, _expectedBufferedByteCount, It.IsAny <AutoResetEvent>(), null), Times.Once);
        }
예제 #17
0
        private void CreateDirectoryRecursively(SftpClient client, string path)
        {
            string current = "";

            if (path[0] == '/')
            {
                path = path.Substring(1);
            }

            while (!string.IsNullOrEmpty(path))
            {
                int p = path.IndexOf('/');
                current += '/';
                if (p >= 0)
                {
                    current += path.Substring(0, p);
                    path     = path.Substring(p + 1);
                }
                else
                {
                    current += path;
                    path     = "";
                }

                try
                {
                    SftpFileAttributes attrs = client.GetAttributes(current);
                    if (!attrs.IsDirectory)
                    {
                        throw new Exception("not directory");
                    }
                }
                catch (SftpPathNotFoundException)
                {
                    client.CreateDirectory(current);
                }
            }
        }
예제 #18
0
파일: Sftp.cs 프로젝트: royedwards/DRDNet
        ///<summary>Loops through the entire path and sees if any directory along the way doesn't exist.  If any don't exist, they get created.</summary>
        public static void CreateDirectoriesIfNeeded(this SftpClient client, string path)
        {
            bool hadToConnect = client.ConnectIfNeeded();

            if (string.IsNullOrEmpty(path))
            {
                return;
            }
            if (path[0] == '/')
            {
                path = path.Substring(1);
            }
            string currentDir = "";

            string[] directories = path.Split('/');
            for (int i = 0; i < directories.Length; i++)
            {
                if (i > 0)
                {
                    currentDir += "/";
                }
                currentDir += directories[i];
                try {
                    //This will throw an exception of SftpPathNotFoundException if the directory does not exist
                    SftpFileAttributes attributes = client.GetAttributes(currentDir);
                    //Check to see if it's a directory.  This will not throw an exception of SftpPathNotFoundException, so we want to break out if it's a file path.
                    //This would be a weird permission issue or implementation error, but it doesn't hurt anything.
                    if (!attributes.IsDirectory)
                    {
                        break;
                    }
                }
                catch (SftpPathNotFoundException) {
                    client.CreateDirectory(currentDir);
                }
            }
            client.DisconnectIfNeeded(hadToConnect);
        }
예제 #19
0
파일: Sftp.cs 프로젝트: royedwards/DRDNet
            protected override async Task PerformIO()
            {
                bool               hadToConnect = _client.ConnectIfNeeded();
                string             fullFilePath = ODFileUtils.CombinePaths(Folder, FileName, '/');
                SftpFileAttributes attribute    = _client.GetAttributes(fullFilePath);

                using (MemoryStream stream = new MemoryStream()) {
                    SftpDownloadAsyncResult res = (SftpDownloadAsyncResult)_client.BeginDownloadFile(fullFilePath, stream);
                    while (!res.AsyncWaitHandle.WaitOne(100))
                    {
                        if (DoCancel)
                        {
                            res.IsDownloadCanceled = true;
                            _client.DisconnectIfNeeded(hadToConnect);
                            return;
                        }
                        OnProgress((double)res.DownloadedBytes / (double)1024 / (double)1024, "?currentVal MB of ?maxVal MB downloaded", (double)attribute.Size / (double)1024 / (double)1024, "");
                    }
                    _client.EndDownloadFile(res);
                    FileContent = stream.ToArray();
                }
                _client.DisconnectIfNeeded(hadToConnect);
                await Task.Run(() => { });                //Gets rid of a compiler warning and does nothing.
            }
        protected void Arrange()
        {
            var random = new Random();

            _path            = random.Next().ToString(CultureInfo.InvariantCulture);
            _handle          = new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) };
            _fileAttributes  = SftpFileAttributes.Empty;
            _bufferSize      = (uint)random.Next(1, 1000);
            _readBufferSize  = (uint)random.Next(0, 1000);
            _writeBufferSize = (uint)random.Next(0, 1000);
            _length          = random.Next();

            _sftpSessionMock = new Mock <ISftpSession>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Truncate, true))
            .Returns(_handle);
            _sftpSessionMock.InSequence(_sequence).Setup(p => p.RequestFStat(_handle)).Returns(_fileAttributes);
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.CalculateOptimalReadLength(_bufferSize))
            .Returns(_readBufferSize);
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle))
            .Returns(_writeBufferSize);
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.IsOpen)
            .Returns(true);

            _sftpFileStream = new SftpFileStream(
                _sftpSessionMock.Object,
                _path,
                FileMode.Create,
                FileAccess.Read,
                (int)_bufferSize);
        }
예제 #21
0
 protected override void LoadData()
 {
     base.LoadData();
     this.Attributes = this.ReadAttributes();
 }
예제 #22
0
        internal SftpContextStream(SftpSession session, string path, FileMode mode, FileAccess access,
                                   SftpFileAttributes attributes)
        {
            Flags flags = Flags.None;

            switch (access)
            {
            case FileAccess.Read:
                flags = Flags.Read;
                break;

            case FileAccess.Write:
                flags = Flags.Write;
                break;

            case FileAccess.ReadWrite:
                flags = Flags.Read | Flags.Write;
                break;
            }

            switch (mode)
            {
            case FileMode.Append:
                flags |= Flags.Append;
                break;

            case FileMode.Create:
                if (attributes == null)
                {
                    flags |= Flags.CreateNew;
                }
                else
                {
                    flags |= Flags.Truncate;
                }
                break;

            case FileMode.CreateNew:
                flags |= Flags.CreateNew;
                break;

            case FileMode.Open:
                break;

            case FileMode.OpenOrCreate:
                flags |= Flags.CreateNewOrOpen;
                break;

            case FileMode.Truncate:
                flags |= Flags.Truncate;
                break;
            }

            _session = session;

            _handle = _session.RequestOpen(path, flags);

            _attributes = attributes ?? _session.RequestFStat(_handle);


            if (access.HasFlag(FileAccess.Write))
            {
                _writeBuffer = new byte[WRITE_BUFFER_SIZE];
                _writeMode   = true;
            }

            _position = mode != FileMode.Append ? 0 : _attributes.Size;
        }
예제 #23
0
 public SftpMkDirRequest(uint requestId, string path, SftpFileAttributes attributes, Action<SftpStatusResponse> statusAction)
     : base(requestId, statusAction)
 {
     this.Path = path;
     this.Attributes = attributes;
 }
예제 #24
0
 protected override void LoadData()
 {
     base.LoadData();
     Attributes = ReadAttributes();
 }
예제 #25
0
        public object ReadProperty(SshPropertyInfo p)
        {
            Type type = p.Information.PropertyType;

            // ordered by most common type.
            if (typeof(Enum).IsAssignableFrom(type) && Enum.GetUnderlyingType(type).Equals(typeof(byte)))
            {
                return(Enum.ToObject(type, this.ReadByte()));
            }
            else if (type.Equals(typeof(string[])))
            {
                return(this.ReadStringAsString().Split(','));
            }
            else if (type.Equals(typeof(string)))
            {
                return(this.ReadStringAsString());
            }
            else if (type.Equals(typeof(uint)))
            {
                return(this.ReadUInt32());
            }
            else if (type.Equals(typeof(byte[])))
            {
                if (p.Attributes.Raw)
                {
                    return(this.ReadBytes(p.Attributes.RawLength));
                }
                else
                {
                    return(this.ReadString());
                }
            }
            else if (type.Equals(typeof(bool)))
            {
                return(this.ReadBoolean());
            }
            else if (typeof(Enum).IsAssignableFrom(type) && Enum.GetUnderlyingType(type).Equals(typeof(uint)))
            {
                return(Enum.ToObject(type, this.ReadUInt32()));
            }
            else if (type.Equals(typeof(short)))
            {
                return(this.ReadInt16());
            }
            else if (type.Equals(typeof(int)))
            {
                return(this.ReadInt32());
            }
            else if (type.Equals(typeof(long)))
            {
                return(this.ReadInt64());
            }
            else if (type.Equals(typeof(ulong)))
            {
                return(this.ReadUInt64());
            }
            else if (type.Equals(typeof(Dictionary <string, string>)))
            {
                var d = new Dictionary <string, string>();
                while (this.Position < this.Length)
                {
                    d.Add(this.ReadStringAsString(), this.ReadStringAsString());
                }
                return(d);
            }
            else if (type.Equals(typeof(SftpFileAttributes)))
            {
                var v = new SftpFileAttributes();
                v.Flags = (FileInfoFlags)this.ReadUInt32();
                if (v.Flags.HasFlag(FileInfoFlags.SSH_FILEXFER_ATTR_PERMISSIONS))
                {
                    v.Permissions = (PermissionsFlags)this.ReadUInt32();
                }
            }
            else if (type.Equals(typeof(SftpFileInfo)))
            {
                return(new SftpFileInfo(this, string.Empty, string.Empty, string.Empty));
            }
            else if (type.Equals(typeof(SftpFileInfo[])))
            {
                var d = new List <SftpFileInfo>();
                while (this.Position < this.Length)
                {
                    d.Add(new SftpFileInfo(this, string.Empty));
                }
                return(d.ToArray());
            }

            return(null);
        }
예제 #26
0
 protected override void LoadData()
 {
     base.LoadData();
     this.Path       = this.ReadString(this.Encoding);
     this.Attributes = this.ReadAttributes();
 }
예제 #27
0
 public SftpContext(SftpFileAttributes attributes, bool aDeleteOnCloseWorkaround)
 {
     _attributes = attributes;
     this.deleteOnCloseWorkaround = aDeleteOnCloseWorkaround;
 }
예제 #28
0
 public SftpContext(SftpFileAttributes attributes)
 {
     _attributes = attributes;
 }
예제 #29
0
        private void download_sftp(string remote_path, string local_path)
        {
            // https://stackoverflow.com/questions/43555982/displaying-progress-of-file-upload-in-a-progressbar-with-ssh-net
            // https://stackoverflow.com/questions/44442714/displaying-progress-of-file-download-in-a-progressbar-with-ssh-net

            download_status = DOWNLOAD_STATUS.start;
            update_ui();

            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();


            SftpClient sftp = new SftpClient(Constants.SFTP_ADDR, Constants.SFTP_ID, Constants.SFTP_PWD);

            try
            {
                using (var stream = new FileStream(local_path, FileMode.Create))
                    using (sftp)
                    {
                        if (!sftp.IsConnected)
                        {
                            sftp.Connect();
                        }
                        SftpFileAttributes attributes = sftp.GetAttributes(remote_path);

                        // Set progress bar maximum on foreground thread
                        Application.Current.Dispatcher.Invoke(() => {
                            var file_size = ByteSize.FromBytes((double)attributes.Size);

                            prgbDownload.Value    = 0;
                            prgbDownload.Maximum  = (int)file_size.Bytes;
                            prgbDownloadText.Text = string.Format("{0} / {1:F1} MB", 0, file_size.MegaBytes);
                        });
                        sftp.DownloadFile(remote_path, stream, download_sftp_progress);
                        extract_zipfile(local_path);

                        download_status = DOWNLOAD_STATUS.end;
                        update_ui();
                    }
            }
            catch (Exception e)
            {
                download_status = DOWNLOAD_STATUS.ini;
                update_ui();
                MessageBox.Show(e.Message);
            }

            stopWatch.Stop();
            TimeSpan ts          = stopWatch.Elapsed;
            string   elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

            if (download_status == DOWNLOAD_STATUS.end)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    prgbDownloadText.Text += "(" + elapsedTime + ")";
                });
            }

            sftp.Dispose();
        }
예제 #30
0
 protected override void LoadData()
 {
     base.LoadData();
     this.Path = this.ReadString();
     this.Attributes = this.ReadAttributes();
 }
예제 #31
0
 public SftpFSetStatRequest(uint protocolVersion, uint requestId, byte[] handle, SftpFileAttributes attributes, Action <SftpStatusResponse> statusAction)
     : base(protocolVersion, requestId, statusAction)
 {
     this.Handle     = handle;
     this.Attributes = attributes;
 }
 public SftpFSetStatRequest(uint protocolVersion, uint requestId, byte[] handle, SftpFileAttributes attributes, Action<SftpStatusResponse> statusAction)
     : base(protocolVersion, requestId, statusAction)
 {
     this.Handle = handle;
     this.Attributes = attributes;
 }
예제 #33
0
        public SftpOpenRequest(uint protocolVersion, uint requestId, string fileName, Encoding encoding, Flags flags, SftpFileAttributes attributes, Action <SftpHandleResponse> handleAction, Action <SftpStatusResponse> statusAction)
            : base(protocolVersion, requestId, statusAction)
        {
            this.Filename   = fileName;
            this.Flags      = flags;
            this.Attributes = attributes;
            this.Encoding   = encoding;

            this.SetAction(handleAction);
        }
 protected override void LoadData()
 {
     base.LoadData();
     this.Handle = this.ReadBinaryString();
     this.Attributes = this.ReadAttributes();
 }
예제 #35
0
 private bool UserCanExecute(SftpFileAttributes attributes)
 {
     return(_userId == -1 || (attributes.OwnerCanExecute && attributes.UserId == _userId ||
                              (attributes.GroupCanExecute && _userGroups.Contains(attributes.GroupId) ||
                               attributes.OthersCanExecute)));
 }
예제 #36
0
 public SftpSetStatRequest(uint protocolVersion, uint requestId, string path, Encoding encoding, SftpFileAttributes attributes, Action <SftpStatusResponse> statusAction)
     : base(protocolVersion, requestId, statusAction)
 {
     this.Encoding   = encoding;
     this.Path       = path;
     this.Attributes = attributes;
 }
예제 #37
0
        private SftpOpenRequest(uint protocolVersion, uint requestId, string fileName, Encoding encoding, Flags flags, SftpFileAttributes attributes, Action <SftpHandleResponse> handleAction, Action <SftpStatusResponse> statusAction)
            : base(protocolVersion, requestId, statusAction)
        {
            Encoding   = encoding;
            Filename   = fileName;
            Flags      = flags;
            Attributes = attributes;

            _handleAction = handleAction;
        }
예제 #38
0
 public void DoRemoteSetFileAttributes(AbstractFileInfo[] files, SftpFileAttributes attr, bool recursive)
 {
     ((ClientSample.Sftp.SftpClientPlugin)_clientPlugin).DoSetFileAttributes(files, attr, recursive);
 }