コード例 #1
1
ファイル: Sftp.cs プロジェクト: royedwards/DRDNet
            protected override async Task PerformIO()
            {
                bool          hadToConnect = _client.ConnectIfNeeded();
                List <string> listFilePaths;
                bool          isDirectory = _client.GetAttributes(FromPath).IsDirectory;

                if (isDirectory)
                {
                    if (DoCancel)
                    {
                        return;
                    }
                    //Only include files (not sub-directories) in the list
                    listFilePaths = (await Task.Factory.FromAsync(_client.BeginListDirectory(FromPath, null, null), _client.EndListDirectory))
                                    .Where(x => !x.IsDirectory)
                                    .Select(x => x.FullName).ToList();
                }
                else                  //Copying a file
                {
                    listFilePaths = new List <string> {
                        FromPath
                    };
                }
                CountTotal = listFilePaths.Count;
                for (int i = 0; i < CountTotal; i++)
                {
                    if (DoCancel)
                    {
                        _client.DisconnectIfNeeded(hadToConnect);
                        return;
                    }
                    string path = listFilePaths[i];
                    try {
                        string fileName   = Path.GetFileName(path);
                        string toPathFull = ToPath;
                        if (isDirectory)
                        {
                            toPathFull = ODFileUtils.CombinePaths(ToPath, fileName, '/');
                        }
                        if (FileExists(_client, toPathFull))
                        {
                            throw new Exception();                            //Throw so that we can iterate CountFailed
                        }
                        string fromPathFull = FromPath;
                        if (isDirectory)
                        {
                            fromPathFull = ODFileUtils.CombinePaths(FromPath, fileName, '/');
                        }
                        if (IsCopy)
                        {
                            //Throws if fails.
                            await Task.Run(() => {
                                TaskStateDownload stateDown = new Download(_host, _user, _pass)
                                {
                                    Folder          = Path.GetDirectoryName(fromPathFull).Replace('\\', '/'),
                                    FileName        = Path.GetFileName(fromPathFull),
                                    ProgressHandler = ProgressHandler,
                                    HasExceptions   = HasExceptions
                                };
                                stateDown.Execute(ProgressHandler != null);
                                while (!stateDown.IsDone)
                                {
                                    stateDown.DoCancel = DoCancel;
                                }
                                if (DoCancel)
                                {
                                    _client.DisconnectIfNeeded(hadToConnect);
                                    return;
                                }
                                TaskStateUpload stateUp = new Upload(_host, _user, _pass)
                                {
                                    Folder          = Path.GetDirectoryName(toPathFull).Replace('\\', '/'),
                                    FileName        = Path.GetFileName(toPathFull),
                                    FileContent     = stateDown.FileContent,
                                    ProgressHandler = ProgressHandler,
                                    HasExceptions   = HasExceptions
                                };
                                stateUp.Execute(ProgressHandler != null);
                                while (!stateUp.IsDone)
                                {
                                    stateUp.DoCancel = DoCancel;
                                }
                                if (DoCancel)
                                {
                                    _client.DisconnectIfNeeded(hadToConnect);
                                    return;
                                }
                            });
                        }
                        else                          //Moving
                        {
                            await Task.Run(() => {
                                SftpFile file = _client.Get(path);
                                _client.CreateDirectoriesIfNeeded(ToPath);
                                file.MoveTo(toPathFull);
                            });
                        }
                        CountSuccess++;
                    }
                    catch (Exception) {
                        CountFailed++;
                    }
                    finally {
                        if (IsCopy)
                        {
                            OnProgress(i + 1, "?currentVal files of ?maxVal files copied", CountTotal, "");
                        }
                        else
                        {
                            OnProgress(i + 1, "?currentVal files of ?maxVal files moved", CountTotal, "");
                        }
                    }
                }
                _client.DisconnectIfNeeded(hadToConnect);
            }
コード例 #2
0
        /// <summary>
        /// Creates the linux directory recursively.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="path">The path.</param>
        /// <exception cref="ArgumentException">Argument path must start with  + LinuxDirectorySeparator.</exception>
        private static void CreateLinuxDirectoryRecursive(SftpClient client, string path)
        {
            if (path.StartsWith(LinuxDirectorySeparator) == false)
            {
                throw new ArgumentException("Argument path must start with " + LinuxDirectorySeparator);
            }

            if (client.Exists(path))
            {
                var info = client.GetAttributes(path);
                if (info.IsDirectory)
                {
                    return;
                }
            }

            var pathParts = path.Split(new[] { LinuxDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);

            pathParts = pathParts.Skip(0).Take(pathParts.Length - 1).ToArray();
            var priorPath = LinuxDirectorySeparator + string.Join(LinuxDirectorySeparator, pathParts);

            if (pathParts.Length > 1)
            {
                CreateLinuxDirectoryRecursive(client, priorPath);
            }

            client.CreateDirectory(path);
        }
コード例 #3
0
ファイル: Sftp.cs プロジェクト: ChemBrain/OpenDental
        ///<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;
            }
            string currentDir = "";

            string[] directories = path.Split("/", StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < directories.Length; i++)
            {
                if (i > 0 || path[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);
        }
コード例 #4
0
        private void downloadWithSFTP(string fileName)
        {
            string host     = parts[1];
            string port     = parts[2];
            string username = parts[3];

            try
            {
                using (Stream stream = new FileStream(getDownloadFolderPath() + @"\" + fileName, FileMode.Create))
                    using (var sftp = new SftpClient(host, Convert.ToInt32(port), username, PasswordTBDownload.Text.ToString()))
                    {
                        sftp.Connect();
                        SftpFileAttributes attributes = sftp.GetAttributes("./" + fileName);
                        var files = sftp.ListDirectory("./");
                        progressBar1.Invoke(
                            (MethodInvoker) delegate { progressBar1.Maximum = (int)attributes.Size; });
                        sftp.DownloadFile(fileName, stream, UpdateProgressBar);
                        MessageBox.Show("Download Complete");

                        sftp.Disconnect();
                        sftp.Dispose();
                    }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Αn Εrror Οccurred", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #5
0
        public bool Upload(string clientPath, string hostPath)
        {
            var fileInfo = new FileInfo(clientPath);
            SftpFileAttributes status;

            try
            {
                status = sftp.GetAttributes(hostPath);
            }
            catch (SftpPathNotFoundException)
            {
                // file does not exist, saves calling exists()
                UploadFile(clientPath, hostPath);
                return(true);
            }

            if (status.Size != fileInfo.Length)
            {
                UploadFile(clientPath, hostPath);
                return(true);
            }

            // file exists and same size, so not going upload
            return(false);
        }
コード例 #6
0
        public StatusCode GetModifiedDateSize(Models.FileTransportInfo transportInformation, out DateTime updateTime, out long lSize)
        {
            lSize      = -1;
            updateTime = DateTime.Today;
            StatusCode retVal = init();

            if (retVal != StatusCode.SUCCEED_STATUS)
            {
                return(retVal);
            }
            SftpClient client = null;

            try
            {
                using (client = new SftpClient(connectionInformation))
                {
                    client.Connect();
                    Renci.SshNet.Sftp.SftpFileAttributes attr = client.GetAttributes(transportInformation.SourceFullName);
                    lSize      = attr.Size;
                    updateTime = attr.LastWriteTime;

                    client.Disconnect();
                }
            }
            catch (Exception ex)
            {
                return(new Common.CommonStatusCode(Common.CommonStatusCode.SFTP_WRITETIME_ERROR, new object[] { connectionInformation.Host, transportInformation.SourceFolderName, transportInformation.SourceFileName }, ex, Config, ApplicationID));
            }
            finally
            {
            }
            return(retVal);
        }
コード例 #7
0
        public string GetFileSize(string filePath)
        {
            using SftpClient sftpClient = CreateSftpClient();

            sftpClient.Connect();

            var length = sftpClient.GetAttributes(filePath).Size.ToString();

            return(length);
        }
コード例 #8
0
        public string GetDateTimestamp(string filePath)
        {
            using SftpClient sftpClient = CreateSftpClient();

            sftpClient.Connect();

            var lastWriteTime = sftpClient.GetAttributes(filePath).LastWriteTime.ToString(CultureInfo.InvariantCulture);

            return(lastWriteTime);
        }
コード例 #9
0
 private bool DestinationDirectoryExists(SftpClient client, string d)
 {
     try
     {
         var attr = client.GetAttributes(d);
         return(attr.IsDirectory);
     }
     catch
     {
         return(false);
     }
 }
コード例 #10
0
        private bool IsFileExistsUsingClient(string filePath, SftpClient sftpClient)
        {
            try
            {
                sftpClient.GetAttributes(filePath);
            }
            catch (SftpPathNotFoundException)
            {
                return(false);
            }

            return(true);
        }
コード例 #11
0
        public long GetFileSize(string path)
        {
            long size = 0;

            try
            {
                size = client.GetAttributes(path).Size;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: \r\n" + ex.ToString());
            }

            return(size);
        }
コード例 #12
0
ファイル: MainActivity.cs プロジェクト: hnjm/OfflineMaps
        ///// <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);
        }
コード例 #13
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);
        }
コード例 #14
0
 public bool ExistsFile(string path)
 {
     try
     {
         using (var sftp = new SftpClient(HostName, Port, UserName, Password))
         {
             sftp.Connect();
             // sftp.ChangeDirectory("/");
             sftp.GetAttributes(path);
             sftp.Disconnect();
         }
     }
     catch (SftpPathNotFoundException)
     {
         return(false);
     }
     return(true);
 }
コード例 #15
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)
         {
         }
     }
 }
コード例 #16
0
        private void DownloadDirectory(SftpClient client, string source, string localPath, bool skipsymlink, Action <ulong> progress)
        {
            var files = client.ListDirectory(source);

            foreach (var file in files)
            {
                if (!file.IsDirectory && !file.IsSymbolicLink)
                {
                    DownloadFile(client, file, localPath, progress);
                }
                else if (file.IsSymbolicLink)
                {
                    var attribs = client.GetAttributes(source);
                    if (skipsymlink)
                    {
                        WriteVerbose($"Skipping symbolic link {file.FullName}");
                    }
                    else
                    {
                        if (attribs.IsDirectory)
                        {
                            var localFullPath = System.IO.Path.Combine(localPath, file.Name);
                            var dir           = Directory.CreateDirectory(localFullPath);
                            DownloadDirectory(client, file.FullName, dir.FullName, skipsymlink, progress);
                        }
                        else if (attribs.IsRegularFile)
                        {
                            DownloadFile(client, file, localPath, progress);
                        }
                    }
                }
                else if (file.Name != "." && file.Name != "..")
                {
                    var localFullPath = System.IO.Path.Combine(localPath, file.Name);
                    var dir           = Directory.CreateDirectory(localFullPath);
                    DownloadDirectory(client, file.FullName, dir.FullName, skipsymlink, progress);
                }
            }
        }
コード例 #17
0
        /// <summary>
        /// Download the specified file from the 3rd party's FTP site
        /// </summary>
        /// <param name="fileToDownload">Name of the file to download</param>
        /// <param name="localFileLocation">Path to the local location to save the file to</param>
        /// <returns></returns>
        public bool DownloadFileUsingSftpClient(string fileToDownload, string localFileLocation)
        {
            _logger.Information($"Downloading File {fileToDownload}...\n", fileToDownload);

            _logger.Verbose($"Local File Location: {localFileLocation}", localFileLocation);
            _logger.Verbose($"File Name: {fileToDownload}", fileToDownload);
            _logger.Verbose($"FTP File Location: {FTPFileLocation}", FTPFileLocation);

            try
            {
                using (var sftp = new SftpClient(FTPHost, FTPUserName, FTPPassword))
                {
                    sftp.Connect();

                    var fullLocalPath = localFileLocation + fileToDownload;
                    var fullSftpPath  = FTPFileLocation + fileToDownload;

                    // If the file already exists in the local directory, compare the dates on the two files
                    if (File.Exists(fullLocalPath))
                    {
                        var newFileInfo      = sftp.GetAttributes(fullSftpPath);
                        var existingFileInfo = new FileInfo(fullLocalPath);

                        if (!ShouldDownloadNewFile(existingFileInfo, newFileInfo))
                        {
                            return(false);
                        }
                    }

                    return(DownloadFile(sftp, fullLocalPath, fullSftpPath));
                }
            }
            catch (Exception ex)
            {
                _logger.ForContext <SftpDownload>().Fatal(ex, "SFTP Download failed.");
                return(false);
            }
        }
コード例 #18
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);
                }
            }
        }
コード例 #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.
            }
コード例 #20
0
        public static List <Element> CheckSFTP(DateTime presentTime, List <Element> SFTP_FilesList)
        {
            List <Element> sftp_filesToProcess = new List <Element>();

            foreach (Element file in SFTP_FilesList)
            {
                file.availableFiles.Clear();
                if (file.way == "download")
                {
                    List <string> availableFiles = new List <string>();
                    bool          hasTimeStamp   = (file.localCommand == "ADD_TIMESTAMP");
                    string        wantedFileName = file.filename;
                    if (hasTimeStamp)
                    {
                        string ext = Path.GetExtension(file.filename);
                        if (ext != "")
                        {
                            wantedFileName = file.filename.Substring(0, file.filename.Length - ext.Length) + "*";
                        }
                    }
                    DirectoryInfo di             = Directory.CreateDirectory(file.localDirectoryPath);
                    List <string> localFilesList = Directory.GetFiles(file.localDirectoryPath, wantedFileName).ToList();

                    using (SftpClient client = new SftpClient(file.home, 22, file.login, file.pw))
                    {
                        try
                        {
                            client.Connect();
                            string workingDirectory = file.remoteDirectory == "" ? "." : file.remoteDirectory;
                            bool   doChangeDir      = (workingDirectory != ".");
                            if (doChangeDir)
                            {
                                client.ChangeDirectory(workingDirectory);
                                workingDirectory = ".";
                            }
                            List <SftpFile> listDirectory = client.ListDirectory(workingDirectory).ToList();
                            foreach (SftpFile aFile in listDirectory)
                            {
                                SftpFileAttributes fileAttributes = client.GetAttributes(aFile.Name);
                                string             remoteFile     = aFile.Name;
                                string             remoteExt      = Path.GetExtension(remoteFile);
                                if (remoteExt != "")
                                {
                                    remoteFile = remoteFile.Substring(0, remoteFile.Length - remoteExt.Length);
                                }
                                string modelFile = file.filename;
                                string modelExt  = Path.GetExtension(modelFile);
                                if (modelExt != "")
                                {
                                    modelFile = modelFile.Substring(0, modelFile.Length - modelExt.Length);
                                }
                                if (remoteFile.Contains(modelFile))
                                {
                                    string pattern           = fileAttributes.LastWriteTime.ToString("yyyyMMddHHmmss") + modelExt;
                                    bool   alreadyDownLoaded = false;
                                    if (localFilesList.Any())
                                    {
                                        foreach (string localFile in localFilesList)
                                        {
                                            if (localFile.Contains(pattern))
                                            {
                                                alreadyDownLoaded = true;
                                            }
                                        }
                                    }
                                    if (!alreadyDownLoaded)
                                    {
                                        availableFiles.Add(aFile.Name);
                                    }
                                }
                            }
                            if (availableFiles.Any())
                            {
                                file.availableFiles.AddRange(availableFiles);
                                sftp_filesToProcess.Add(file);
                            }
                        }
                        catch (Exception er)
                        {
                            LogManager.GetLogger("SERVICE").Info("SSH.NET exception" + er.ToString());
                        }
                        finally
                        {
                            client.Disconnect();
                        }
                    }
                }
                else if (file.way == "upload")
                {
                    string wantedFileName   = file.filename;
                    bool   hasFileToProcess = false;
                    bool   hasTimeStamp     = (file.localCommand == "REMOVE_DATESTAMP" || file.localCommand == "REMOVE_TIMESTAMP");
                    if (hasTimeStamp)
                    {
                        string ext = Path.GetExtension(file.filename);
                        if (ext != "")
                        {
                            wantedFileName = file.filename.Substring(0, file.filename.Length - ext.Length) + "*";
                        }
                    }
                    DirectoryInfo di = Directory.CreateDirectory(file.localDirectoryPath);

                    List <string> localFilesList = new List <string>();
                    try
                    {
                        localFilesList = Directory.GetFiles(file.localDirectoryPath, wantedFileName).ToList();
                        if (localFilesList != null)
                        {
                            if (localFilesList.Any())
                            {
                                hasFileToProcess = true;
                            }
                        }
                    }
                    catch (DirectoryNotFoundException ex)
                    {
                        LogManager.GetLogger("ERROR").InfoFormat(ex.Message);
                        LogManager.GetLogger("ERROR").InfoFormat("Cannot process file {0} !", file.filename);
                    }
                    if (hasFileToProcess)
                    {
                        using (SftpClient client = new SftpClient(file.home, 22, file.login, file.pw))
                        {
                            bool doProcess = true;
                            try
                            {
                                client.Connect();
                                string workingDirectory = file.remoteDirectory == "" ? "." : file.remoteDirectory;
                                bool   doChangeDir      = (workingDirectory != ".");
                                if (doChangeDir)
                                {
                                    client.ChangeDirectory(workingDirectory);
                                    workingDirectory = ".";
                                }
                                List <SftpFile> listDirectory = client.ListDirectory(workingDirectory).ToList();
                                foreach (SftpFile aFile in listDirectory)
                                {
                                    if (aFile.Name == file.filename && file.remoteCommand == "NO_OVERWRITE")
                                    {
                                        doProcess = false;
                                    }
                                }
                                if (doProcess)
                                {
                                    if (file.remoteCommand == "NO_OVERWRITE")
                                    {
                                        file.availableFiles.Add(localFilesList[0]);
                                    }
                                    else
                                    {
                                        foreach (string localFile in localFilesList)
                                        {
                                            file.availableFiles.Add(localFile);
                                        }
                                    }
                                    sftp_filesToProcess.Add(file);
                                }
                            }
                            catch (Exception er)
                            {
                                LogManager.GetLogger("SERVICE").Info("SSH.NET exception" + er.ToString());
                            }
                            finally
                            {
                                client.Disconnect();
                            }
                        }
                    }
                }
            }
            return(sftp_filesToProcess);
        }
コード例 #21
0
ファイル: Form1.cs プロジェクト: Fabio3rs/SFTPSyncFiles
        void SyncDirectory(SftpClient client, string localPath, string remotePath)
        {
            client.BufferSize = 16 * 1024;

            if (debugTextOutput)
            {
                Console.WriteLine("Uploading directory {0} to {1}", localPath, remotePath);
            }

            IEnumerable <FileSystemInfo> infos =
                new DirectoryInfo(localPath).EnumerateFileSystemInfos();

            foreach (FileSystemInfo info in infos)
            {
                if (info.Attributes.HasFlag(FileAttributes.Directory))
                {
                    string subPath = remotePath + "/" + info.Name;
                    if (!client.Exists(subPath))
                    {
                        client.CreateDirectory(subPath);
                    }
                    SyncDirectory(client, info.FullName, remotePath + "/" + info.Name);
                }
                else
                {
                    Renci.SshNet.Sftp.SftpFileAttributes attr;

                    bool supload = true;
                    try
                    {
                        if (client.Exists(remotePath + "/" + info.Name))
                        {
                            attr = client.GetAttributes(remotePath + "/" + info.Name);

                            FileInfo finfo = (FileInfo)info;

                            if (finfo.Length == attr.Size)
                            {
                                DateTime dt  = finfo.LastWriteTime;
                                DateTime dt1 = attr.LastWriteTime;

                                //System.Windows.Forms.MessageBox.Show(info.Name + "  " + dt.ToString() + "   " + dt1.ToString());
                                if (dt <= dt1)
                                {
                                    supload = false;
                                }
                            }
                        }

                        list_wa[syncingWatcherId].uploadingfile = info.FullName;
                    }
                    catch (Exception ex)
                    {
                        System.Windows.Forms.MessageBox.Show(ex.Message + "  " + info.Name);
                    }

                    if (supload)
                    {
                        using (FileStream fileStream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            /*String s = String.Format(
                             *  "Uploading {0} ({1:N0} bytes)\n",
                             *  info.FullName, ((FileInfo)info).Length);
                             *
                             * AppendTextBox(s);*/
                            list_wa[syncingWatcherId].resetUploadData((ulong)fileStream.Length);
                            list_wa[syncingWatcherId].uploadingfile = info.FullName;
                            client.UploadFile(fileStream, remotePath + "/" + info.Name, list_wa[syncingWatcherId].uploadcb);
                            list_wa[syncingWatcherId].uploadingfile = "";
                        }
                    }
                }
            }
            list_wa[syncingWatcherId].uploadingfile = "";
        }
コード例 #22
0
        private void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            if (!client.IsConnected)
            {
                reconnectTimer.Interval = 500;
                reconnectTimer.Enabled  = true;
                System.Threading.Thread.Sleep(3000);

                if (!client.IsConnected)
                {
                    return;
                }
            }

            try
            {
                client.BufferSize = 16 * 1024;
                mut.WaitOne();

                if (!client.IsConnected)
                {
                    try
                    {
                        client.Connect();
                    }
                    catch (Exception ex)
                    {
                        interf.AppendTextBox(ex.Message + "   " + ex.StackTrace + "   " + ex.Source + "\n\n\n\n");
                        mut.ReleaseMutex();
                        return;
                    }
                }

                aTimer.Stop();

                // Sorting the file list makes sure the actions are applied to the parent directory first
                List <FileSystemEventArgs> SortedList = fse.OrderBy(o => o.FullPath).ToList();

                for (int i = 0; i < SortedList.Count; i++)
                {
                    FileSystemEventArgs f = SortedList[i];

                    if (f == null)
                    {
                        continue;
                    }

                    string fpath = f.FullPath.Replace(path, "");
                    fpath = fpath.Replace("\\", "/");
                    //System.Windows.Forms.MessageBox.Show(f.Name + "   " + fpath + "  " + f.ChangeType.ToString());

                    if (f.ChangeType != WatcherChangeTypes.Deleted)
                    {
                        FileAttributes attr = FileAttributes.Directory;

                        try
                        {
                            attr = File.GetAttributes(f.FullPath);
                        }
                        catch (Exception ex)
                        {
                            interf.AppendTextBox(ex.Message);
                            continue;
                        }

                        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            try
                            {
                                string spath = serverpath + fpath;
                                if (!client.Exists(spath))
                                {
                                    client.CreateDirectory(spath);
                                }
                            }
                            catch (Exception ex)
                            {
                                interf.AppendTextBox(ex.Message);
                            }

                            DirSearchF(f.FullPath);

                            for (int j = i + 1; j < SortedList.Count; j++)
                            {
                                string bsl = "\\";

                                if (f.FullPath.Contains("/"))
                                {
                                    bsl = "/";
                                }

                                if (f.FullPath.EndsWith(bsl))
                                {
                                    bsl = "";
                                }

                                bool ischilddir = SortedList[j].FullPath == f.FullPath ? true : SortedList[j].FullPath.StartsWith(f.FullPath + bsl);

                                if (ischilddir)
                                {
                                    //SortedList[j] = null;
                                    SortedList.RemoveAt(j);
                                    j--;
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                string fmtname = Path.GetDirectoryName(f.FullPath);
                                fmtname = fmtname.Replace(path, "");
                                fmtname = fmtname.Replace("\\\\", "/");
                                fmtname = fmtname.Replace("\\", "/");
                                //string lfname = StringUtils.RemoveFromEnd(fpath, fmtname);
                                string svfullpath = serverpath + fmtname;

                                RecursiveSVMkdir(svfullpath);

                                using (FileStream fs = new FileStream(f.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                                {
                                    resetUploadData((ulong)fs.Length);
                                    uploadingfile = f.FullPath;
                                    client.UploadFile(fs, serverpath + fpath, uploadcb);
                                }
                            }
                            catch (Exception ex)
                            {
                                interf.AppendTextBox(ex.Message + "   " + ex.StackTrace + "   " + ex.Source + "\n\n\n\n");
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            string spath = serverpath + fpath;
                            if (client.Exists(spath))
                            {
                                bool isdirectory = client.GetAttributes(spath).IsDirectory;

                                client.RenameFile(spath, spath + ".file_deleted");

                                if (isdirectory)
                                {
                                    for (int j = i + 1; j < SortedList.Count; j++)
                                    {
                                        string bsl = "\\";

                                        if (f.FullPath.Contains("/"))
                                        {
                                            bsl = "/";
                                        }

                                        if (f.FullPath.EndsWith(bsl))
                                        {
                                            bsl = "";
                                        }

                                        bool ischilddir = SortedList[j].FullPath == f.FullPath ? true : SortedList[j].FullPath.StartsWith(f.FullPath + bsl);

                                        if (ischilddir)
                                        {
                                            SortedList[j] = null;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            interf.AppendTextBox(ex.Message);
                            continue;
                        }
                    }
                }
                uploadingfile = "";
                fse.Clear();
            }
            catch (Exception ex)
            {
                interf.AppendTextBox(ex.Message);
            }

            mut.ReleaseMutex();
        }
コード例 #23
0
        /// <summary>
        /// Download method using SSH.NET SFTP implementation for async files downloading.
        /// </summary>
        private void DOWNLOAD(SftpClient client, String remoteFileName)
        {
            bool IsExists = client.Exists(remoteFileName);

            Modify_DownloadStatusTextBox(DownloadStatusTextBox, System.Environment.NewLine + "Checking if remote file " + remoteFileName + " exists..." + System.Environment.NewLine);

            if (IsExists)
            {
                Console.WriteLine("File exists... continue!");
                Modify_DownloadStatusTextBox(DownloadStatusTextBox, "File exists..." + System.Environment.NewLine);

                SftpFileAttributes att = client.GetAttributes(remoteFileName);
                fileSize = att.Size;
                Modify_DownloadStatusTextBox(DownloadStatusTextBox, "File size is: " + fileSize + "." + System.Environment.NewLine);

                Console.WriteLine("File size is: " + fileSize);

                string name          = remoteFileName;
                int    pos           = name.LastIndexOf("/") + 1;
                String localFileName = DownloadPathTextbox.Text + "/" + name.Substring(pos, name.Length - pos);

                using (FileStream fs = new FileStream(localFileName, FileMode.Create, FileAccess.Write))
                {
                    Console.WriteLine("Begin Async Download!");
                    Modify_DownloadStatusTextBox(DownloadStatusTextBox, "Downloading file " + remoteFileName + " ..." + System.Environment.NewLine);

                    IAsyncResult asyncr = client.BeginDownloadFile(remoteFileName, fs);
                    sftpAsyncr = (SftpDownloadAsyncResult)asyncr;


                    while (!sftpAsyncr.IsCompleted && !sftpAsyncr.IsDownloadCanceled)
                    {
                        int pct = Convert.ToInt32(((double)sftpAsyncr.DownloadedBytes / (double)fileSize) * 100);

                        double temp = (double)sftpAsyncr.DownloadedBytes / (double)fileSize;
                        Console.WriteLine("Downloaded Bytes: " + sftpAsyncr.DownloadedBytes);
                        Console.WriteLine("Downloaded: " + temp);
                        Console.WriteLine("File size is: " + fileSize);
                        Console.WriteLine(pct);
                        Modify_progressBar1(progressBar1, pct);
                        Modify_DownloadLabel(DownloadLabel, "Status: " + pct + " %");
                        Modify_DownloadBytesLabel(DownloadBytesLabel, sftpAsyncr.DownloadedBytes);
                    }
                    client.EndDownloadFile(asyncr);

                    fs.Close();
                }

                if (sftpAsyncr.IsDownloadCanceled)
                {
                    Console.WriteLine("File Download has been canceled!");
                    Modify_DownloadStatusTextBox(DownloadStatusTextBox, "File Download has been canceled!" + System.Environment.NewLine);
                }
                else
                {
                    Console.WriteLine("The file " + remoteFileName + " has been successfully downloaded from the server");
                    Modify_DownloadStatusTextBox(DownloadStatusTextBox, "The file " + remoteFileName + " has been downloaded successfully!" + System.Environment.NewLine);
                }
            }
            else
            {
                MessageBox.Show("The file " + remoteFileName + " does not exists on the server.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #24
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();
        }
コード例 #25
0
ファイル: SftpClientTest.cs プロジェクト: pecegit/sshnet
 public void GetAttributesTest()
 {
     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
     SftpFileAttributes expected = null; // TODO: Initialize to an appropriate value
     SftpFileAttributes actual;
     actual = target.GetAttributes(path);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
コード例 #26
0
        public static void ProcessSFTP(DateTime presentTime, List <Element> sftp_filesToProcess)
        {
            string          fileDateEnd = presentTime.ToString("yyyyMMdd");
            List <Archiver> toArchive   = new List <Archiver>();

            foreach (Element file in sftp_filesToProcess)
            {
                if (file.way == "download")
                {
                    DirectoryInfo di = Directory.CreateDirectory(file.localDirectoryPath);

                    using (SftpClient client = new SftpClient(file.home, 22, file.login, file.pw))
                    {
                        try
                        {
                            client.Connect();
                            string workingDirectory = file.remoteDirectory == "" ? "." : file.remoteDirectory;
                            bool   doChangeDir      = (workingDirectory != ".");
                            if (doChangeDir)
                            {
                                client.ChangeDirectory(workingDirectory);
                                workingDirectory = ".";
                            }
                            foreach (string filename in file.availableFiles)
                            {
                                string destFile = filename;
                                if (file.localCommand == "ADD_TIMESTAMP")
                                {
                                    string ext = Path.GetExtension(filename);
                                    if (ext != "")
                                    {
                                        destFile = filename.Substring(0, file.filename.Length - ext.Length);
                                    }
                                    if (ext == "")
                                    {
                                        string modelExt = Path.GetExtension(file.filename);
                                        if (modelExt != "")
                                        {
                                            ext = modelExt;
                                        }
                                    }
                                    SftpFileAttributes fileAttributes = client.GetAttributes(filename);
                                    destFile += "_" + fileAttributes.LastWriteTime.ToString("yyyyMMddHHmmss") + ext;
                                }
                                destFile = Path.Combine(file.localDirectoryPath, destFile);
                                using (Stream file2get = File.OpenWrite(destFile))
                                {
                                    client.DownloadFile(Path.GetFileName(filename), file2get);
                                }
                                LogManager.GetLogger("SERVICE").InfoFormat("File {0} downloaded", Path.GetFileName(destFile));
                            }
                        }
                        catch (Exception er)
                        {
                            LogManager.GetLogger("SERVICE").Info("SSH.NET exception" + er.ToString());
                        }
                        finally
                        {
                            client.Disconnect();
                        }
                    }
                }
                else if (file.way == "upload") // nolimit
                {
                    DirectoryInfo di = Directory.CreateDirectory(file.localDoneDirectoryPath);

                    using (SftpClient client = new SftpClient(file.home, 22, file.login, file.pw))
                    {
                        try
                        {
                            client.Connect();
                            string workingDirectory = file.remoteDirectory == "" ? "." : file.remoteDirectory;
                            bool   doChangeDir      = (workingDirectory != ".");
                            if (doChangeDir)
                            {
                                client.ChangeDirectory(workingDirectory);
                                workingDirectory = ".";
                            }
                            foreach (string filepath in file.availableFiles)
                            {
                                using (Stream fileStream = new FileStream(filepath, FileMode.Open))
                                {
                                    client.BufferSize = 512 * 1024; // bypass Payload error large files
                                    client.UploadFile(fileStream, file.filename);

                                    LogManager.GetLogger("SERVICE").InfoFormat("File {0} uploaded", file.filename);

                                    if (file.localDoneDirectoryPath != null && file.localDoneDirectoryPath != "") // à archiver à la fin
                                    {
                                        string destFile = Path.Combine(file.localDoneDirectoryPath, Path.GetFileName(filepath));
                                        toArchive.Add(new Archiver
                                        {
                                            SourceFile = filepath,
                                            DestFile   = destFile
                                        });
                                    }
                                }
                            }
                        }
                        catch (Exception er)
                        {
                            LogManager.GetLogger("SERVICE").Info("SSH.NET exception" + er.ToString());
                        }
                        finally
                        {
                            client.Disconnect();
                        }
                    }
                }
            }
            if (toArchive.Any())
            {
                foreach (Archiver arch in toArchive)
                {
                    int    cpt           = 1;
                    string ext           = "";
                    string filenameWoExt = arch.DestFile;
                    if (File.Exists(arch.DestFile))
                    {
                        ext = Path.GetExtension(arch.DestFile);
                        if (ext != "")
                        {
                            filenameWoExt = arch.DestFile.Substring(0, arch.DestFile.Length - ext.Length);
                        }
                    }
                    while (File.Exists(arch.DestFile))
                    {
                        cpt++;
                        arch.DestFile = string.Format("{0}({1}){2}", filenameWoExt, cpt, ext);
                    }
                    File.Move(arch.SourceFile, arch.DestFile);
                    LogManager.GetLogger("SERVICE").InfoFormat("Uploaded File {0} archived ", Path.GetFileName(arch.SourceFile));
                }
            }
        }
コード例 #27
0
        public NtStatus CreateFile(string fileName, FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, DokanFileInfo info)
        {
            //Debug.WriteLine(@"{0} : {1} {2}", fileName, mode.ToString(), access.ToString());

            fileName = ToUnixStylePath(fileName);

            if (fileName.EndsWith("desktop.ini", StringComparison.OrdinalIgnoreCase) ||
                fileName.EndsWith("autorun.inf", StringComparison.OrdinalIgnoreCase))
            {
                return(DokanResult.FileNotFound);
            }

            bool exists = sftpClient.Exists(fileName);

            // todo : add to memory cache

            if (info.IsDirectory)
            {
                try
                {
                    switch (mode)
                    {
                    case FileMode.Open:
                        if (!exists)
                        {
                            return(DokanResult.PathNotFound);
                        }

                        break;

                    case FileMode.CreateNew:
                        if (exists)
                        {
                            return(DokanResult.FileExists);
                        }

                        sftpClient.CreateDirectory(fileName);

                        break;
                    }
                }
                catch (Renci.SshNet.Common.SshException)
                {
                    return(DokanResult.AccessDenied);
                }
            }
            else
            {
                bool readWriteAttributes = (access & DataAccess) == 0;
                bool readAccess          = (access & DataWriteAccess) == 0;
                System.IO.FileAccess acs = readAccess ? System.IO.FileAccess.Read : System.IO.FileAccess.ReadWrite;

                switch (mode)
                {
                case FileMode.Open:

                    if (!exists)
                    {
                        return(DokanResult.FileNotFound);
                    }

                    SftpFileAttributes attr = sftpClient.GetAttributes(fileName);
                    if (readWriteAttributes || attr.IsDirectory)
                    {
                        info.IsDirectory = attr.IsDirectory;
                        info.Context     = new object();
                        return(DokanResult.Success);
                    }

                    break;

                case FileMode.CreateNew:
                    if (exists)
                    {
                        return(DokanResult.FileExists);
                    }

                    // cache invalidate

                    break;

                case FileMode.Truncate:
                    if (!exists)
                    {
                        return(DokanResult.FileNotFound);
                    }

                    // cache invalidate

                    break;

                default:
                    // cache invalidate
                    break;
                }

                try
                {
                    info.Context = sftpClient.Open(fileName, mode, acs) as SftpFileStream;
                }
                catch (Renci.SshNet.Common.SshException)
                {
                    return(DokanResult.AccessDenied);
                }
            }

            return(DokanResult.Success);
        }
コード例 #28
0
 public static async Task <SftpFileAttributes> GetAttributesAsync(this SftpClient client, string path)
 {
     return(await Task.Factory.StartNew(() => client.GetAttributes(path)));
 }