Гость
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / net core работа с FTP / 6 сообщений из 6, страница 1 из 1
28.09.2016, 10:10
    #39316721
angel_zar
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
net core работа с FTP
Раньше использовал System.Net.FTPclient
Кто что может подсказать по сабжу в теме?
...
Рейтинг: 0 / 0
28.09.2016, 10:51
    #39316748
hVostt
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
net core работа с FTP
angel_zarРаньше использовал System.Net.FTPclient
Кто что может подсказать по сабжу в теме?

В Core пока нет поддержки FTP.
...
Рейтинг: 0 / 0
28.09.2016, 12:15
    #39316828
angel_zar
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
net core работа с FTP
hVosttВ Core пока нет поддержки FTP.
Интересно нафига тогда они это в описании держат
тынц
...
Рейтинг: 0 / 0
28.09.2016, 13:22
    #39316877
Где-то в степи
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
net core работа с FTP
angel_zar,
может и поможет - деталь проекта

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
307.
308.
309.
310.
311.
312.
313.
314.
315.
316.
317.
318.
319.
320.
321.
322.
323.
324.
325.
326.
327.
328.
329.
330.
331.
332.
333.
334.
335.
336.
337.
338.
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
366.
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
379.
380.
381.
382.
383.
384.
385.
386.
387.
388.
389.
390.
391.
392.
393.
394.
395.
396.
397.
398.
399.
400.
401.
402.
403.
404.
405.
406.
407.
408.
409.
410.
411.
412.
413.
414.
415.
416.
417.
418.
419.
420.
421.
422.
423.
424.
425.
426.
427.
428.
429.
430.
431.
432.
433.
434.
435.
436.
437.
438.
439.
440.
441.
442.
443.
444.
445.
446.
447.
448.
449.
450.
451.
452.
453.
454.
455.
456.
457.
458.
459.
460.
461.
462.
463.
464.
465.
466.
467.
468.
469.
470.
471.
472.
473.
474.
475.
476.
477.
478.
479.
480.
481.
482.
483.
484.
485.
486.
487.
488.
489.
490.
491.
492.
493.
494.
495.
496.
497.
498.
499.
500.
501.
502.
503.
504.
505.
506.
507.
508.
509.
510.
511.
#region License Information (GPL v3)

/*
    ShareX - A program that allows you to take screenshots and share any file type
    Copyright (C) 2007-2014 ShareX Developers

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

    Optionally you can also view the license at <http://www.gnu.org/licenses/>.
*/

#endregion License Information (GPL v3)

using HelpersLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using UploadersLib.HelperClasses;

namespace UploadersLib
{
    public class FTPOptions
    {
        public FTPOptions()
        {
        }

        public FTPOptions(FTPAccount acc, IWebProxy proxy)
        {
            Account = acc;
            ProxySettings = proxy;
        }

        public FTPAccount Account { get; set; }

        public IWebProxy ProxySettings { get; set; }
    }

    public class FTPAdapter
    {
        public event ProgressEventHandler ProgressChanged;

        public delegate void ProgressEventHandler(ProgressManager progress);

        public event StringEventHandler FTPOutput;

        public delegate void StringEventHandler(string text);

        public FTPOptions Options;

        private const int BufferSize = 2048;

        public FTPAdapter(FTPOptions options)
        {
            Options = options;
        }

        private void OnProgressChanged(ProgressManager progress)
        {
            if (ProgressChanged != null)
            {
                ProgressChanged(progress);
            }
        }

        public bool Upload(Stream stream, string url)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
                request.Proxy = Options.ProxySettings;
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
                request.KeepAlive = false;
                request.UsePassive = !Options.Account.IsActive;

                using (stream)
                using (Stream requestStream = request.GetRequestStream())
                {
                    ProgressManager progress = new ProgressManager(stream.Length);

                    byte[] buffer = new byte[BufferSize];
                    int bytesRead;

                    while ((bytesRead = stream.Read(buffer, 0, BufferSize)) > 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                        progress.UpdateProgress(bytesRead);
                        OnProgressChanged(progress);
                    }
                }

                WriteOutput("Upload: " + url);
                return true;
            }
            catch (Exception ex)
            {
                WriteOutput(string.Format("Error: {0} - Upload: {1}", ex.Message, url));
            }
            return false;
        }

        public bool UploadFile(string filePath, string url)
        {
            FileStream stream = new FileStream(filePath, FileMode.Open);
            return Upload(stream, url);
        }

        public bool UploadText(string text, string url)
        {
            MemoryStream stream = new MemoryStream(Encoding.Default.GetBytes(text), false);
            return Upload(stream, url);
        }

        #region Async Methods

        private class AsyncUploadHelper
        {
            public BackgroundWorker BackgroundWorker;
            public Stream Stream;
            public string URL;
        }

        public void AsyncUpload(Stream stream, string url)
        {
            BackgroundWorker bw = new BackgroundWorker { WorkerReportsProgress = true };
            bw.DoWork += bw_AsyncUploadDoWork;
            bw.ProgressChanged += bw_AsyncUploadProgressChanged;
            AsyncUploadHelper upload = new AsyncUploadHelper { BackgroundWorker = bw, Stream = stream, URL = url };
            bw.RunWorkerAsync(upload);
        }

        private void bw_AsyncUploadDoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                AsyncUploadHelper upload = (AsyncUploadHelper)e.Argument;

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(upload.URL);
                request.Proxy = Options.ProxySettings;
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
                request.KeepAlive = false;
                request.UsePassive = !Options.Account.IsActive;

                using (upload.Stream)
                using (Stream requestStream = request.GetRequestStream())
                {
                    ProgressManager progress = new ProgressManager(upload.Stream.Length);

                    byte[] buffer = new byte[BufferSize];
                    int bytesRead;

                    while ((bytesRead = upload.Stream.Read(buffer, 0, BufferSize)) > 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                        progress.UpdateProgress(bytesRead);
                        upload.BackgroundWorker.ReportProgress((int)progress.Percentage, progress);
                    }
                }
            }
            catch (Exception ex)
            {
                DebugHelper.WriteException(ex);
            }
        }

        private void bw_AsyncUploadProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (ProgressChanged != null)
            {
                ProgressChanged((ProgressManager)e.UserState);
            }
        }

        public void AsyncUploadFile(string filePath, string url)
        {
            FileStream stream = new FileStream(filePath, FileMode.Open);
            AsyncUpload(stream, url);
        }

        public void AsyncUploadText(string text, string url)
        {
            MemoryStream stream = new MemoryStream(Encoding.Default.GetBytes(text), false);
            AsyncUpload(stream, url);
        }

        #endregion Async Methods

        public bool DownloadFile(string url, string savePath)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
                request.Proxy = Options.ProxySettings;
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
                request.KeepAlive = false;
                request.UsePassive = !Options.Account.IsActive;

                using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                {
                    ProgressManager progress = new ProgressManager(stream.Length);

                    byte[] buffer = new byte[BufferSize];
                    int bytesRead;

                    while ((bytesRead = stream.Read(buffer, 0, BufferSize)) > 0)
                    {
                        fileStream.Write(buffer, 0, bytesRead);
                        progress.UpdateProgress(bytesRead);
                        OnProgressChanged(progress);
                    }
                }

                WriteOutput(string.Format("DownloadFile: {0} -> {1}", url, savePath));
                return true;
            }
            catch (Exception ex)
            {
                WriteOutput(string.Format("Error: {0} - DownloadFile: {1} -> {2}", ex.Message, url, savePath));
            }
            return false;
        }

        public void DeleteFile(string url)
        {
            string filename = URLHelpers.GetFileName(url);
            if (filename == "." || filename == "..") return;

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
            request.Proxy = Options.ProxySettings;
            request.Method = WebRequestMethods.Ftp.DeleteFile;
            request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
            request.KeepAlive = false;

            request.GetResponse();

            WriteOutput("DeleteFile: " + url);
        }

        public void RemoveDirectory(string url)
        {
            string filename = URLHelpers.GetFileName(url);
            if (filename == "." || filename == "..") return;

            List<FTPLineResult> files = ListDirectoryDetails(url);
            string path = URLHelpers.GetDirectoryPath(url);

            foreach (FTPLineResult file in files)
            {
                if (file.IsDirectory)
                {
                    RemoveDirectory(URLHelpers.CombineURL(url, file.Name));
                }
                else
                {
                    DeleteFile(URLHelpers.CombineURL(url, file.Name));
                }
            }

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
            request.Proxy = Options.ProxySettings;
            request.Method = WebRequestMethods.Ftp.RemoveDirectory;
            request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
            request.KeepAlive = false;

            request.GetResponse();

            WriteOutput("RemoveDirectory: " + url);
        }

        public void Rename(string url, string newFileName)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
            request.Proxy = Options.ProxySettings;
            request.Method = WebRequestMethods.Ftp.Rename;
            request.RenameTo = newFileName;
            request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
            request.KeepAlive = false;

            request.GetResponse();

            WriteOutput(string.Format("Rename: {0} -> {1}", url, newFileName));
        }

        public long GetFileSize(string url)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
            request.Proxy = Options.ProxySettings;
            request.Method = WebRequestMethods.Ftp.GetFileSize;
            request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
            request.KeepAlive = false;

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                WriteOutput("GetFileSize: " + url);

                return response.ContentLength;
            }
        }

        public string[] ListDirectory(string url)
        {
            List<string> result = new List<string>();

            url = URLHelpers.AddSlash(url, SlashType.Suffix);

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
            request.Proxy = Options.ProxySettings;
            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
            request.KeepAlive = false;
            request.Timeout = 10000;
            request.UsePassive = !Options.Account.IsActive;

            using (WebResponse response = request.GetResponse())
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                while (!reader.EndOfStream)
                {
                    result.Add(reader.ReadLine());
                }

                WriteOutput("ListDirectory: " + url);

                return result.ToArray();
            }
        }

        public List<FTPLineResult> ListDirectoryDetails(string url)
        {
            List<FTPLineResult> result = new List<FTPLineResult>();

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
            request.Proxy = Options.ProxySettings;
            request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
            request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
            request.KeepAlive = false;
            request.UsePassive = !Options.Account.IsActive;

            using (WebResponse response = request.GetResponse())
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                while (!reader.EndOfStream)
                {
                    result.Add(FTPLineParser.Parse(reader.ReadLine()));
                }

                WriteOutput("ListDirectoryDetails: " + url);

                return result;
            }
        }

        public bool MakeDirectory(string url)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);

                request.Method = WebRequestMethods.Ftp.MakeDirectory;
                request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
                request.KeepAlive = false;

                request.GetResponse();

                WriteOutput("MakeDirectory: " + url);
                return true;
            }
            catch (Exception ex)
            {
                WriteOutput(string.Format("Error: {0} - MakeDirectory: {1}", ex.Message, url));
            }
            return false;
        }

        public void MakeMultiDirectory(string dirName)
        {
            string path = "";
            string[] dirs = dirName.Split('/');
            foreach (string dir in dirs)
            {
                if (!string.IsNullOrEmpty(dir))
                {
                    path = URLHelpers.CombineURL(path, dir);
                    MakeDirectory(URLHelpers.CombineURL(Options.Account.FTPAddress, path));
                }
            }

            WriteOutput("MakeMultiDirectory: " + dirName);
        }

        public void WriteOutput(string text)
        {
            if (FTPOutput != null)
            {
                FTPOutput(string.Format("{0} - {1}", FastDateTime.Now.ToLongTimeString(), text));
            }
        }
    }

    public static class FTPLineParser
    {
        private static Regex unixStyle = new Regex(@"^(?<Permissions>(?<Directory>[-dl])(?<OwnerPerm>[-r][-w][-x])(?<GroupPerm>[-r][-w][-x])(?<EveryonePerm>[-r][-w][-x]))\s+(?<FileType>\d+)\s+(?<Owner>\w+)\s+(?<Group>\w+)\s+(?<Size>\d+)\s+(?<Month>\w+)\s+(?<Day>\d{1,2})\s+(?<Year>(?<Hour>\d{1,2}):*(?<Minutes>\d{1,2}))\s+(?<Name>.*)$");
        private static Regex winStyle = new Regex(@"^(?<Month>\d{1,2})-(?<Day>\d{1,2})-(?<Year>\d{1,2})\s+(?<Hour>\d{1,2}):(?<Minutes>\d{1,2})(?<ampm>am|pm)\s+(?<Dir>[<]dir[>])?\s+(?<Size>\d+)?\s+(?<Name>.*)$");

        public static FTPLineResult Parse(string line)
        {
            Match match = unixStyle.Match(line);
            if (match.Success)
            {
                return ParseMatch(match.Groups, ListStyle.Unix);
            }

            throw new Exception("Only support Unix ftp servers.");

            /*
            match = winStyle.Match(line);
            if (match.Success)
            {
                return ParseMatch(match.Groups, ListStyle.Windows);
            }

            throw new Exception("Invalid line format");
            */
        }

        private static FTPLineResult ParseMatch(GroupCollection matchGroups, ListStyle style)
        {
            FTPLineResult result = new FTPLineResult();

            result.Style = style;
            string dirMatch = style == ListStyle.Unix ? "d" : "<dir>";
            result.IsDirectory = matchGroups["Directory"].Value.Equals(dirMatch, StringComparison.InvariantCultureIgnoreCase);
            result.Permissions = matchGroups["Permissions"].Value;
            result.Name = matchGroups["Name"].Value;

            if (!result.IsDirectory)
            {
                result.SetSize(matchGroups["Size"].Value);
            }

            result.Owner = matchGroups["Owner"].Value;
            result.Group = matchGroups["Group"].Value;
            result.SetDateTime(matchGroups["Year"].Value, matchGroups["Month"].Value, matchGroups["Day"].Value);

            return result;
        }
    }

    public enum ListStyle
    {
        Unix,
        Windows
    }

    public class FTPLineResult
    {
        public ListStyle Style;
        public string Name;
        public string Permissions;
        public DateTime DateTime;
        public bool TimeInfo;
        public bool IsDirectory;
        public long Size;
        public string SizeString;
        public string Owner;
        public string Group;
        public bool IsSpecial;

        public void SetSize(string size)
        {
            Size = long.Parse(size);
            SizeString = Size.ToString("N0");
        }

        public void SetDateTime(string year, string month, string day)
        {
            string time = string.Empty;

            if (year.Contains(":"))
            {
                time = year;
                year = FastDateTime.Now.Year.ToString();
                TimeInfo = true;
            }

            DateTime = DateTime.Parse(string.Format("{0}/{1}/{2} {3}", year, month, day, time));
            DateTime = DateTime.ToLocalTime();
        }
    }
}


...
Рейтинг: 0 / 0
28.09.2016, 13:26
    #39316881
hVostt
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
net core работа с FTP
angel_zarhVosttВ Core пока нет поддержки FTP.
Интересно нафига тогда они это в описании держат
тынц

Там две ветки разработки. Одна ветка реализуется поверх существующего фреймворка, там доступны все функции, как нугет-пакеты, и доступк ФТП в том числе. В ветке Core этой реализации нет, пока.
...
Рейтинг: 0 / 0
28.09.2016, 14:24
    #39316948
angel_zar
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
net core работа с FTP
Где-то в степиможет и поможет - деталь проекта

FtpWebRequest нет такого в core
Я уже тоже изучал разные самоделки. Везде упираешься в этот FtpWebRequest
...
Рейтинг: 0 / 0
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / net core работа с FTP / 6 сообщений из 6, страница 1 из 1
Целевая тема:
Создать новую тему:
Автор:
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]