コード例 #1
0
        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);

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

            var 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);
            _sftpSessionMock.InSequence(sequence)
            .Setup(p => p.RequestClose(_handle));

            _sftpFileStream = new SftpFileStream(_sftpSessionMock.Object, _path, FileMode.Create, FileAccess.Read, (int)_bufferSize);
            _sftpFileStream.Close();
        }
コード例 #2
0
        private bool UploadStream(Stream stream, string remotePath, bool autoCreateDirectory = false)
        {
            if (Connect())
            {
                try
                {
                    using (SftpFileStream sftpStream = client.Create(remotePath))
                    {
                        return(TransferData(stream, sftpStream));
                    }
                }
                catch (SftpPathNotFoundException) when(autoCreateDirectory)
                {
                    // Happens when directory not exist, create directory and retry uploading

                    CreateDirectory(URLHelpers.GetDirectoryPath(remotePath), true);
                    return(UploadStream(stream, remotePath));
                }
                catch (NullReferenceException)
                {
                    // Happens when disconnect while uploading
                }
            }

            return(false);
        }
コード例 #3
0
 private void UploadStream(Stream stream, string path)
 {
     using (SftpFileStream sftpStream = client.OpenWrite(path))
     {
         TransferData(stream, sftpStream);
     }
 }
コード例 #4
0
        protected override void Arrange()
        {
            base.Arrange();

            _target = new SftpFileStream(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize);
            _target.Read(_buffer, 0, _buffer.Length);
        }
コード例 #5
0
        protected override void Arrange()
        {
            base.Arrange();

            _sftpFileStream = new SftpFileStream(SftpSessionMock.Object, _path, FileMode.Open, FileAccess.ReadWrite, (int)_bufferSize);
            _sftpFileStream.Read(_readBytes, 0, _readBytes.Length);
        }
コード例 #6
0
 protected override void Act()
 {
     _target = new SftpFileStream(SftpSessionMock.Object,
                                  _path,
                                  _fileMode,
                                  _fileAccess,
                                  _bufferSize);
 }
        protected override void Arrange()
        {
            base.Arrange();

            _sftpFileStream = new SftpFileStream(SftpSessionMock.Object, _path, FileMode.Open, FileAccess.ReadWrite, (int)_bufferSize);
            _sftpFileStream.Read(_readBytes1, 0, _readBytes1.Length);
            _sftpFileStream.Read(_readBytes2, 0, _readBytes2.Length); // this will return bytes from the buffer
        }
コード例 #8
0
 public override void OpenFileForReading(string name)
 {
     if (fileStream != null)
     {
         throw new Exception("Can't happen");
     }
     fileName             = FullPathWithName(name);
     fileStream           = sftpClient.OpenRead(WireEncodedString(fileName));
     fileLastWriteTimeUtc = DateTime.MinValue;
 }
コード例 #9
0
        public void CloseTest()
        {
            SftpSession    session = null;                                    // TODO: Initialize to an appropriate value
            string         path    = string.Empty;                            // TODO: Initialize to an appropriate value
            FileMode       mode    = new FileMode();                          // TODO: Initialize to an appropriate value
            SftpFileStream target  = new SftpFileStream(session, path, mode); // TODO: Initialize to an appropriate value

            target.Close();
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
        protected override void Arrange()
        {
            base.Arrange();

            _target = new SftpFileStream(SftpSessionMock.Object,
                                         _path,
                                         FileMode.Open,
                                         FileAccess.Read,
                                         (int)_bufferSize);
        }
コード例 #11
0
        public void LengthTest()
        {
            SftpSession    session = null;                                    // TODO: Initialize to an appropriate value
            string         path    = string.Empty;                            // TODO: Initialize to an appropriate value
            FileMode       mode    = new FileMode();                          // TODO: Initialize to an appropriate value
            SftpFileStream target  = new SftpFileStream(session, path, mode); // TODO: Initialize to an appropriate value
            long           actual;

            actual = target.Length;
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
コード例 #12
0
        protected override void Arrange()
        {
            base.Arrange();

            _target = new SftpFileStream(SftpSessionMock.Object,
                                         _path,
                                         FileMode.OpenOrCreate,
                                         FileAccess.Write,
                                         (int)_bufferSize);
            _target.Dispose();
        }
コード例 #13
0
        protected override void Arrange()
        {
            base.Arrange();

            _target = new SftpFileStream(SftpSessionMock.Object,
                                         _path,
                                         FileMode.Open,
                                         FileAccess.ReadWrite,
                                         (int)_bufferSize);
            _target.Write(_writeBytes1, 0, _writeBytes1.Length);
            _target.Write(_writeBytes2, 0, _writeBytes2.Length);
            _target.Write(_writeBytes3, 0, _writeBytes3.Length);
        }
コード例 #14
0
        public void ReadByteTest()
        {
            SftpSession    session  = null;                                    // TODO: Initialize to an appropriate value
            string         path     = string.Empty;                            // TODO: Initialize to an appropriate value
            FileMode       mode     = new FileMode();                          // TODO: Initialize to an appropriate value
            SftpFileStream target   = new SftpFileStream(session, path, mode); // TODO: Initialize to an appropriate value
            int            expected = 0;                                       // TODO: Initialize to an appropriate value
            int            actual;

            actual = target.ReadByte();
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
コード例 #15
0
        public void WriteTest()
        {
            SftpSession    session = null;                                    // TODO: Initialize to an appropriate value
            string         path    = string.Empty;                            // TODO: Initialize to an appropriate value
            FileMode       mode    = new FileMode();                          // TODO: Initialize to an appropriate value
            SftpFileStream target  = new SftpFileStream(session, path, mode); // TODO: Initialize to an appropriate value

            byte[] buffer = null;                                             // TODO: Initialize to an appropriate value
            int    offset = 0;                                                // TODO: Initialize to an appropriate value
            int    count  = 0;                                                // TODO: Initialize to an appropriate value

            target.Write(buffer, offset, count);
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
        protected void Arrange()
        {
            var random = new Random();

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

            _fileAttributesLastAccessTime = DateTime.UtcNow.AddSeconds(random.Next());
            _fileAttributesLastWriteTime  = DateTime.UtcNow.AddSeconds(random.Next());
            _fileAttributesSize           = random.Next();
            _fileAttributesUserId         = random.Next();
            _fileAttributesGroupId        = random.Next();
            _fileAttributesPermissions    = (uint)random.Next();
            _fileAttributesExtensions     = new Dictionary <string, string>();
            _fileAttributes = new SftpFileAttributes(_fileAttributesLastAccessTime,
                                                     _fileAttributesLastWriteTime,
                                                     _fileAttributesSize,
                                                     _fileAttributesUserId,
                                                     _fileAttributesGroupId,
                                                     _fileAttributesPermissions,
                                                     _fileAttributesExtensions);

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

            _sequence = new MockSequence();
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write | Flags.Truncate, true))
            .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.RequestFStat(_handle, false))
            .Returns(_fileAttributes);
            _sftpSessionMock.InSequence(_sequence)
            .Setup(p => p.RequestFSetStat(_handle, _fileAttributes))
            .Callback <byte[], SftpFileAttributes>((bytes, attributes) => _lengthPassedToRequestFSetStat = attributes.Size);

            _sftpFileStream = new SftpFileStream(_sftpSessionMock.Object, _path, FileMode.Create, FileAccess.ReadWrite, (int)_bufferSize);
        }
コード例 #17
0
 public override void CloseFile()
 {
     if (fileStream != null)
     {
         bool wasWriting = fileStream.CanWrite && !fileStream.CanRead;
         fileStream.Close();
         if (wasWriting)
         {
             sftpClient.SetLastWriteTimeUtc(WireEncodedString(fileName), fileLastWriteTimeUtc);
         }
     }
     fileName             = null;
     fileStream           = null;
     fileLastWriteTimeUtc = DateTime.MinValue;
 }
コード例 #18
0
        public void SeekTest()
        {
            SftpSession    session  = null;                                    // TODO: Initialize to an appropriate value
            string         path     = string.Empty;                            // TODO: Initialize to an appropriate value
            FileMode       mode     = new FileMode();                          // TODO: Initialize to an appropriate value
            SftpFileStream target   = new SftpFileStream(session, path, mode); // TODO: Initialize to an appropriate value
            long           offset   = 0;                                       // TODO: Initialize to an appropriate value
            SeekOrigin     origin   = new SeekOrigin();                        // TODO: Initialize to an appropriate value
            long           expected = 0;                                       // TODO: Initialize to an appropriate value
            long           actual;

            actual = target.Seek(offset, origin);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
コード例 #19
0
        private static async Task <string> ReadData(SftpFileStream stream)
        {
            var dataToRead = stream.Length - stream.Position;

            using (var reader = new StreamReader(stream, leaveOpen: true))
            {
                if (dataToRead > maxRead)
                {
                    var buffer = new char[maxRead];
                    var read   = await reader.ReadAsync(buffer, 0, maxRead);

                    return(new string(buffer, 0, read));
                }
                return(await reader.ReadToEndAsync());
            }
        }
        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);
        }
コード例 #21
0
ファイル: UnraidApiClient.cs プロジェクト: Hertizch/UnraidApi
        /// <summary>
        /// Open SFTP connection to server and download specified file to string
        /// </summary>
        /// <param name="filePath">Filename to download</param>
        /// <returns>File contents string</returns>
        internal async Task <string> ReadRemoteFile(string filePath, bool refreshHttp = false, bool invokeEmHttp = false)
        {
            string         output           = null;
            SftpFileStream remoteFileStream = null;

            // Check if we need to update the http page before getting our file
            if (refreshHttp)
            {
                await RefreshHttpPage($"http://{Host}", "/Docker");
            }

            // Check if we need to invoke the emhttpd script before getting our file
            if (invokeEmHttp)
            {
                await InvokeEmHttp();
            }

            await Task.Run(async() =>
            {
                try
                {
                    if (!_sftpClient.IsConnected)
                    {
                        _sftpClient.Connect();
                    }

                    remoteFileStream = _sftpClient.OpenRead(filePath);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"[ERROR] [UnraidApiClient.ReadRemoteFile(string {filePath})] EXCEPTION: {ex.Message}");
                }
                finally
                {
                    if (remoteFileStream != null)
                    {
                        output = await new StreamReader(remoteFileStream).ReadToEndAsync();
                    }
                }
            });

            //Debug.WriteLine($"[DEBUG] [UnraidApiClient.ReadRemoteFile(string {filePath})] RETURNED: {output}");

            return(output);
        }
コード例 #22
0
    public SftpFileStream GetRemoteFile(string filename)
    {
        // Server credentials
        var host     = "host";
        var port     = 22;
        var username = "******";
        var password = "******";

        sftp = new SftpClient(host, port, username, password);

        // Connect to the SFTP server
        sftp.Connect();

        // Read the file in question
        file = sftp.OpenRead(filename);

        return(file);
    }
コード例 #23
0
        public void BeginWriteTest()
        {
            SftpSession    session = null;                                    // TODO: Initialize to an appropriate value
            string         path    = string.Empty;                            // TODO: Initialize to an appropriate value
            FileMode       mode    = new FileMode();                          // TODO: Initialize to an appropriate value
            SftpFileStream target  = new SftpFileStream(session, path, mode); // TODO: Initialize to an appropriate value

            byte[]        buffer   = null;                                    // TODO: Initialize to an appropriate value
            int           offset   = 0;                                       // TODO: Initialize to an appropriate value
            int           count    = 0;                                       // TODO: Initialize to an appropriate value
            AsyncCallback callback = null;                                    // TODO: Initialize to an appropriate value
            object        state    = null;                                    // TODO: Initialize to an appropriate value
            IAsyncResult  expected = null;                                    // TODO: Initialize to an appropriate value
            IAsyncResult  actual;

            actual = target.BeginWrite(buffer, offset, count, callback, state);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
コード例 #24
0
        public NtStatus WriteFile(string fileName, byte[] buffer, out int bytesWritten, long offset, DokanFileInfo info)
        {
            if (info.Context == null)
            {
                using (SftpFileStream stream = sftpClient.Open(fileName, FileMode.Open, System.IO.FileAccess.Write))
                {
                    stream.Position = offset;
                    stream.Write(buffer, 0, buffer.Length);
                    bytesWritten = buffer.Length;
                }
            }
            else
            {
                var stream = info.Context as SftpFileStream;
                stream.Write(buffer, 0, buffer.Length);
                bytesWritten = buffer.Length;
            }

            return(DokanResult.Success);
        }
コード例 #25
0
        public SFTPStream(Uri uri, ConnectionInfo connectionInfo, StreamMode streamMode)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (connectionInfo == null)
            {
                throw new ArgumentNullException(nameof(connectionInfo));
            }

            _uri    = uri;
            _client = new SftpClient(connectionInfo);

            _client.Connect();

            String adjustedLocalPath = uri.LocalPath.Substring(1);

            _stream = streamMode == StreamMode.Read ? _client.OpenRead(adjustedLocalPath) : _client.Create(adjustedLocalPath);
        }
コード例 #26
0
ファイル: SFtpClient.cs プロジェクト: sinfar/OPS
        public void DownloadFile(string remotePath, string localPath, AsyncCallback callback)
        {
            SftpFileStream inSt  = null;
            FileStream     outSt = null;

            try
            {
                SftpFile file     = sftp.Get(remotePath);
                long     fileSize = file.Length;

                inSt  = sftp.OpenRead(remotePath);
                outSt = new FileStream(localPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

                byte[] buf   = new byte[8092];
                int    len   = 0;
                long   count = 0;
                while ((len = inSt.Read(buf, 0, 8092)) > 0)
                {
                    outSt.Write(buf, 0, len);
                    count += len;

                    if (callback != null) // 下载进度回调通知
                    {
                        DownloadAsyncResult result = new DownloadAsyncResult(count, fileSize);
                        callback.Invoke(result);
                    }
                }
            }
            finally
            {
                if (inSt != null)
                {
                    inSt.Close();
                }
                if (outSt != null)
                {
                    outSt.Close();
                }
            }
        }
コード例 #27
0
        public NtStatus ReadFile(string fileName, byte[] buffer, out int bytesRead, long offset, DokanFileInfo info)
        {
            Debug.Print("read : {0} offset : {1}", fileName, offset);
            if (info.Context == null)
            {
                using (SftpFileStream stream = sftpClient.Open(ToUnixStylePath(fileName), FileMode.Open, System.IO.FileAccess.Read))
                {
                    stream.Position = offset;
                    bytesRead       = stream.Read(buffer, 0, buffer.Length);
                }
            }
            else
            {
                SftpFileStream stream = info.Context as SftpFileStream;
                lock (stream)
                {
                    stream.Position = offset;
                    bytesRead       = stream.Read(buffer, 0, buffer.Length);
                }
            }

            return(DokanResult.Success);
        }
コード例 #28
0
        private bool UploadStream(Stream stream, string remotePath)
        {
            if (Connect())
            {
                try
                {
                    using (SftpFileStream sftpStream = client.OpenWrite(remotePath))
                    {
                        return(TransferData(stream, sftpStream));
                    }
                }
                catch (SftpPathNotFoundException)
                {
                    CreateDirectory(URLHelpers.GetDirectoryPath(remotePath));

                    using (SftpFileStream sftpStream = client.OpenWrite(remotePath))
                    {
                        return(TransferData(stream, sftpStream));
                    }
                }
            }

            return(false);
        }
コード例 #29
0
 public SshFileStream(SftpFileStream fs)
 {
     _fs = fs;
 }