├── README.md
├── IOExtensions
├── IOExtensions.nuspec
├── Properties
│ └── AssemblyInfo.cs
├── TransferProgress.cs
├── NativeMethods.cs
├── AccessRightsChecker.cs
├── IOExtensions.csproj
├── Helpers.cs
└── FileTransferManager.cs
├── LICENSE
├── IOExtensions.sln
└── .gitignore
/README.md:
--------------------------------------------------------------------------------
1 | # FileTransferManager
2 | C# lib for copying/moving files and folders with reporting a progress
3 |
4 | Supports sync and async invoking
5 |
6 | Provides functionality to check access rights for a given folder
7 |
8 | [](https://www.nuget.org/packages/FileTransferManager) on [NuGet](https://www.nuget.org/packages/FileTransferManager)
9 |
--------------------------------------------------------------------------------
/IOExtensions/IOExtensions.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | FileTransferManager
5 | $version$
6 | $title$
7 | Martin Chrzan
8 | Martin Chrzan
9 | MIT
10 | https://github.com/martinchrzan/FileTransferManager
11 | false
12 | $description$
13 |
14 | Added cancellation token into MoveWithProgressAsync, fixed cancellation within copy operations.
15 | Signed libraries.
16 | Moved to .NET Framework 4.7.2
17 |
18 | Martin Chrzan copyright 2019-2021
19 | Copy Move File Directory Progress
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 martinchrzan
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/IOExtensions.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.28010.2050
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IOExtensions", "IOExtensions\IOExtensions.csproj", "{CF3ADDC6-0809-4FF6-B5E5-E40189D2BB34}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {CF3ADDC6-0809-4FF6-B5E5-E40189D2BB34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {CF3ADDC6-0809-4FF6-B5E5-E40189D2BB34}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {CF3ADDC6-0809-4FF6-B5E5-E40189D2BB34}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {CF3ADDC6-0809-4FF6-B5E5-E40189D2BB34}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {B6A8D92C-ABB0-4B0F-9BCD-DC2F97C5C6EA}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/IOExtensions/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("FileTransferManager")]
9 | [assembly: AssemblyDescription("Copy and move files/folders functionality with reporting a progress")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Martin Chrzan")]
12 | [assembly: AssemblyProduct("IOExtensions")]
13 | [assembly: AssemblyCopyright("Martin Chrzan © 2019-2021")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("cf3addc6-0809-4ff6-b5e5-e40189d2bb34")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.6.0")]
36 | [assembly: AssemblyFileVersion("1.0.6.0")]
37 |
--------------------------------------------------------------------------------
/IOExtensions/TransferProgress.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace IOExtensions
4 | {
5 | public class TransferProgress
6 | {
7 | public TransferProgress(DateTime startedTimestamp, long bytesTransfered)
8 | {
9 | BytesTransferred = bytesTransfered;
10 | BytesPerSecond = BytesTransferred / DateTime.Now.Subtract(startedTimestamp).TotalSeconds;
11 | }
12 |
13 | public long Total { get; set; }
14 |
15 | public long Transferred { get; set; }
16 |
17 | public long BytesTransferred { get; set; }
18 |
19 | public long StreamSize { get; set; }
20 |
21 | public string ProcessedFile { get; set; }
22 |
23 | public double BytesPerSecond { get; }
24 |
25 | public double Fraction
26 | {
27 | get
28 | {
29 | return BytesTransferred / (double)Total;
30 | }
31 | }
32 |
33 | public double Percentage
34 | {
35 | get
36 | {
37 | return 100.0 * Fraction;
38 | }
39 | }
40 |
41 | public string GetBytesTransferedFormatted(SuffixStyle suffixStyle, int decimalPlaces)
42 | {
43 | return Helpers.ToSizeWithSuffix(BytesTransferred, suffixStyle, decimalPlaces);
44 | }
45 |
46 | public string GetDataPerSecondFormatted(SuffixStyle suffixStyle, int decimalPlaces)
47 | {
48 | return string.Format("{0}/sec", Helpers.ToSizeWithSuffix((long)BytesPerSecond, suffixStyle, decimalPlaces));
49 | }
50 |
51 | public override string ToString()
52 | {
53 | return string.Format("Total: {0}, BytesTransferred: {1}, Percentage: {2}", Total, BytesTransferred, Percentage);
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/IOExtensions/NativeMethods.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace IOExtensions
5 | {
6 | internal static class NativeMethods
7 | {
8 | [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
9 | internal static extern bool MoveFileWithProgress(string lpExistingFileName, string lpNewFileName, CopyProgressRoutine lpProgressRoutine, IntPtr lpData, MoveFileFlags dwCopyFlags);
10 |
11 | [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
12 | [return: MarshalAs(UnmanagedType.Bool)]
13 | internal static extern bool CopyFileEx(string lpExistingFileName, string lpNewFileName, CopyProgressRoutine lpProgressRoutine, IntPtr lpData, ref int pbCancel, CopyFileFlags dwCopyFlags);
14 |
15 | internal delegate CopyProgressResult CopyProgressRoutine(long TotalFileSize, long TotalBytesTransferred, long StreamSize, long StreamBytesTransferred, uint dwStreamNumber, CopyProgressCallbackReason dwCallbackReason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData);
16 |
17 | internal enum CopyProgressResult : uint
18 | {
19 | PROGRESS_CONTINUE,
20 | PROGRESS_CANCEL,
21 | PROGRESS_STOP,
22 | PROGRESS_QUIET,
23 | }
24 |
25 | internal enum CopyProgressCallbackReason : uint
26 | {
27 | CALLBACK_CHUNK_FINISHED,
28 | CALLBACK_STREAM_SWITCH,
29 | }
30 |
31 | [Flags]
32 | internal enum MoveFileFlags : uint
33 | {
34 | MOVE_FILE_REPLACE_EXISTSING = 1,
35 | MOVE_FILE_COPY_ALLOWED = 2,
36 | MOVE_FILE_DELAY_UNTIL_REBOOT = 4,
37 | MOVE_FILE_WRITE_THROUGH = 8,
38 | MOVE_FILE_CREATE_HARDLINK = 16, // 0x00000010
39 | MOVE_FILE_FAIL_IF_NOT_TRACKABLE = 32, // 0x00000020
40 | }
41 |
42 | [Flags]
43 | internal enum CopyFileFlags : uint
44 | {
45 | COPY_FILE_FAIL_IF_EXISTS = 1,
46 | COPY_FILE_RESTARTABLE = 2,
47 | COPY_FILE_OPEN_SOURCE_FOR_WRITE = 4,
48 | COPY_FILE_ALLOW_DECRYPTED_DESTINATION = 8,
49 | COPY_FILE_COPY_SYMLINK = 2048, // 0x00000800
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/IOExtensions/AccessRightsChecker.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | using System.Security.AccessControl;
3 | using System.Security.Principal;
4 |
5 | namespace IOExtensions
6 | {
7 | public static class AccessRightsChecker
8 | {
9 | ///
10 | /// Test a directory or file for file access permissions
11 | ///
12 | /// Full path to file or directory
13 | /// File System right tested
14 | /// State [bool]
15 | public static bool ItemHasPermision(string itemPath, FileSystemRights accessRight)
16 | {
17 | if (string.IsNullOrEmpty(itemPath)) return false;
18 | var isDir = itemPath.IsDirFile();
19 | if (isDir == null) return false;
20 |
21 | try
22 | {
23 | AuthorizationRuleCollection rules;
24 | if (isDir == true)
25 | {
26 | rules = Directory.GetAccessControl(itemPath).GetAccessRules(true, true, typeof(SecurityIdentifier));
27 | }
28 | else
29 | {
30 | rules = File.GetAccessControl(itemPath).GetAccessRules(true, true, typeof(SecurityIdentifier));
31 | }
32 |
33 | var identity = WindowsIdentity.GetCurrent();
34 | string userSID = identity.User.Value;
35 |
36 | foreach (FileSystemAccessRule rule in rules)
37 | {
38 | if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
39 | {
40 | if ((accessRight & rule.FileSystemRights) == accessRight)
41 | {
42 | if (rule.AccessControlType == AccessControlType.Deny)
43 | {
44 | return false;
45 | }
46 |
47 | if (rule.AccessControlType == AccessControlType.Allow)
48 | return true;
49 | }
50 | }
51 | }
52 | }
53 | catch { }
54 | return false;
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/IOExtensions/IOExtensions.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {CF3ADDC6-0809-4FF6-B5E5-E40189D2BB34}
8 | Library
9 | Properties
10 | IOExtensions
11 | IOExtensions
12 | v4.7.2
13 | 512
14 | true
15 |
16 |
17 |
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 | 5.9.1
55 | runtime; build; native; contentfiles; analyzers; buildtransitive
56 | all
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/IOExtensions/Helpers.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace IOExtensions
5 | {
6 | public enum SuffixStyle { Windows, Binary, Metric }
7 |
8 | internal static class Helpers
9 | {
10 | // 1 KB = 1024 bytes
11 | private static readonly string[] SizeWindowsSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
12 |
13 | // 1 KiB = 1024 bytes
14 | private static readonly string[] SizeBinarySuffixes = { "bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB" };
15 |
16 | // 1 kB = 1000 bytes
17 | private static readonly string[] SizeMetricSuffixes = { "bytes", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
18 |
19 | internal static string ToSizeWithSuffix(long value, SuffixStyle style, int decimalPlaces = 1)
20 | {
21 | var newBase = 1024;
22 | if (style == SuffixStyle.Metric)
23 | {
24 | newBase = 1000;
25 | }
26 |
27 | if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
28 | if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }
29 |
30 | // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
31 | int mag = (int)Math.Log(value, newBase);
32 |
33 | // 1L << (mag * 10) == 2 ^ (10 * mag)
34 | // [i.e. the number of bytes in the unit corresponding to mag]
35 | decimal adjustedSize = (decimal)value / (1L << (mag * 10));
36 |
37 | if (style == SuffixStyle.Metric)
38 | {
39 | adjustedSize = value / (decimal)(Math.Pow(newBase, mag));
40 | }
41 |
42 | // make adjustment when the value is large enough that
43 | // it would round up to higher magnitude
44 | if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
45 | {
46 | mag += 1;
47 | adjustedSize /= newBase;
48 | }
49 |
50 | return string.Format("{0:n" + decimalPlaces + "} {1}",
51 | adjustedSize,
52 | GetSuffixAtIndex(style, mag));
53 | }
54 |
55 | private static string GetSuffixAtIndex(SuffixStyle style, int index)
56 | {
57 | switch (style)
58 | {
59 | case SuffixStyle.Binary:
60 | return SizeBinarySuffixes[index];
61 | case SuffixStyle.Metric:
62 | return SizeMetricSuffixes[index];
63 | case SuffixStyle.Windows:
64 | return SizeWindowsSuffixes[index];
65 | }
66 | return string.Empty;
67 | }
68 |
69 | // Returns true if the path is a dir, false if it's a file and null if it's neither or doesn't exist.
70 | internal static bool? IsDirFile(this string path)
71 | {
72 | bool? result = null; if (Directory.Exists(path) || File.Exists(path))
73 | {
74 | // get the file attributes for file or directory
75 | var fileAttr = File.GetAttributes(path);
76 | if (fileAttr.HasFlag(FileAttributes.Directory))
77 | result = true;
78 | else result = false;
79 | }
80 | return result;
81 | }
82 |
83 | // corrects destination path for folder if provided destination is only directory not a full filename
84 | internal static string CorrectFileDestinationPath(string source, string destination)
85 | {
86 | var destinationFile = destination;
87 | if (destination.IsDirFile() == true)
88 | {
89 | destinationFile = Path.Combine(destination, Path.GetFileName(source));
90 | }
91 | return destinationFile;
92 | }
93 |
94 |
95 | internal static DirectorySizeInfo DirSize(DirectoryInfo d)
96 | {
97 | DirectorySizeInfo size = new DirectorySizeInfo();
98 |
99 | try
100 | {
101 | // Add file sizes.
102 | var fis = d.GetFiles();
103 | foreach (var fi in fis)
104 | {
105 | size.Size += fi.Length;
106 | }
107 | size.FileCount += fis.Length;
108 |
109 | // Add subdirectory sizes.
110 | var dis = d.GetDirectories();
111 | size.DirectoryCount += dis.Length;
112 | foreach (var di in dis)
113 | {
114 | size += DirSize(di);
115 | }
116 | }
117 | catch
118 | {
119 | }
120 |
121 | return size;
122 | }
123 |
124 | internal sealed class DirectorySizeInfo
125 | {
126 | public long FileCount = 0;
127 | public long DirectoryCount = 0;
128 | public long Size = 0;
129 |
130 | public static DirectorySizeInfo operator +(DirectorySizeInfo s1, DirectorySizeInfo s2)
131 | {
132 | return new DirectorySizeInfo()
133 | {
134 | DirectoryCount = s1.DirectoryCount + s2.DirectoryCount,
135 | FileCount = s1.FileCount + s2.FileCount,
136 | Size = s1.Size + s2.Size
137 | };
138 | }
139 | }
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015/2017 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # Visual Studio 2017 auto generated files
33 | Generated\ Files/
34 |
35 | # MSTest test Results
36 | [Tt]est[Rr]esult*/
37 | [Bb]uild[Ll]og.*
38 |
39 | # NUNIT
40 | *.VisualState.xml
41 | TestResult.xml
42 |
43 | # Build Results of an ATL Project
44 | [Dd]ebugPS/
45 | [Rr]eleasePS/
46 | dlldata.c
47 |
48 | # Benchmark Results
49 | BenchmarkDotNet.Artifacts/
50 |
51 | # .NET Core
52 | project.lock.json
53 | project.fragment.lock.json
54 | artifacts/
55 | **/Properties/launchSettings.json
56 |
57 | # StyleCop
58 | StyleCopReport.xml
59 |
60 | # Files built by Visual Studio
61 | *_i.c
62 | *_p.c
63 | *_i.h
64 | *.ilk
65 | *.meta
66 | *.obj
67 | *.iobj
68 | *.pch
69 | *.pdb
70 | *.ipdb
71 | *.pgc
72 | *.pgd
73 | *.rsp
74 | *.sbr
75 | *.tlb
76 | *.tli
77 | *.tlh
78 | *.tmp
79 | *.tmp_proj
80 | *.log
81 | *.vspscc
82 | *.vssscc
83 | .builds
84 | *.pidb
85 | *.svclog
86 | *.scc
87 |
88 | # Chutzpah Test files
89 | _Chutzpah*
90 |
91 | # Visual C++ cache files
92 | ipch/
93 | *.aps
94 | *.ncb
95 | *.opendb
96 | *.opensdf
97 | *.sdf
98 | *.cachefile
99 | *.VC.db
100 | *.VC.VC.opendb
101 |
102 | # Visual Studio profiler
103 | *.psess
104 | *.vsp
105 | *.vspx
106 | *.sap
107 |
108 | # Visual Studio Trace Files
109 | *.e2e
110 |
111 | # TFS 2012 Local Workspace
112 | $tf/
113 |
114 | # Guidance Automation Toolkit
115 | *.gpState
116 |
117 | # ReSharper is a .NET coding add-in
118 | _ReSharper*/
119 | *.[Rr]e[Ss]harper
120 | *.DotSettings.user
121 |
122 | # JustCode is a .NET coding add-in
123 | .JustCode
124 |
125 | # TeamCity is a build add-in
126 | _TeamCity*
127 |
128 | # DotCover is a Code Coverage Tool
129 | *.dotCover
130 |
131 | # AxoCover is a Code Coverage Tool
132 | .axoCover/*
133 | !.axoCover/settings.json
134 |
135 | # Visual Studio code coverage results
136 | *.coverage
137 | *.coveragexml
138 |
139 | # NCrunch
140 | _NCrunch_*
141 | .*crunch*.local.xml
142 | nCrunchTemp_*
143 |
144 | # MightyMoose
145 | *.mm.*
146 | AutoTest.Net/
147 |
148 | # Web workbench (sass)
149 | .sass-cache/
150 |
151 | # Installshield output folder
152 | [Ee]xpress/
153 |
154 | # DocProject is a documentation generator add-in
155 | DocProject/buildhelp/
156 | DocProject/Help/*.HxT
157 | DocProject/Help/*.HxC
158 | DocProject/Help/*.hhc
159 | DocProject/Help/*.hhk
160 | DocProject/Help/*.hhp
161 | DocProject/Help/Html2
162 | DocProject/Help/html
163 |
164 | # Click-Once directory
165 | publish/
166 |
167 | # Publish Web Output
168 | *.[Pp]ublish.xml
169 | *.azurePubxml
170 | # Note: Comment the next line if you want to checkin your web deploy settings,
171 | # but database connection strings (with potential passwords) will be unencrypted
172 | *.pubxml
173 | *.publishproj
174 |
175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
176 | # checkin your Azure Web App publish settings, but sensitive information contained
177 | # in these scripts will be unencrypted
178 | PublishScripts/
179 |
180 | # NuGet Packages
181 | *.nupkg
182 | # The packages folder can be ignored because of Package Restore
183 | **/[Pp]ackages/*
184 | # except build/, which is used as an MSBuild target.
185 | !**/[Pp]ackages/build/
186 | # Uncomment if necessary however generally it will be regenerated when needed
187 | #!**/[Pp]ackages/repositories.config
188 | # NuGet v3's project.json files produces more ignorable files
189 | *.nuget.props
190 | *.nuget.targets
191 |
192 | # Microsoft Azure Build Output
193 | csx/
194 | *.build.csdef
195 |
196 | # Microsoft Azure Emulator
197 | ecf/
198 | rcf/
199 |
200 | # Windows Store app package directories and files
201 | AppPackages/
202 | BundleArtifacts/
203 | Package.StoreAssociation.xml
204 | _pkginfo.txt
205 | *.appx
206 |
207 | # Visual Studio cache files
208 | # files ending in .cache can be ignored
209 | *.[Cc]ache
210 | # but keep track of directories ending in .cache
211 | !*.[Cc]ache/
212 |
213 | # Others
214 | ClientBin/
215 | ~$*
216 | *~
217 | *.dbmdl
218 | *.dbproj.schemaview
219 | *.jfm
220 | *.pfx
221 | *.publishsettings
222 | orleans.codegen.cs
223 |
224 | # Including strong name files can present a security risk
225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
226 | #*.snk
227 |
228 | # Since there are multiple workflows, uncomment next line to ignore bower_components
229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
230 | #bower_components/
231 |
232 | # RIA/Silverlight projects
233 | Generated_Code/
234 |
235 | # Backup & report files from converting an old project file
236 | # to a newer Visual Studio version. Backup files are not needed,
237 | # because we have git ;-)
238 | _UpgradeReport_Files/
239 | Backup*/
240 | UpgradeLog*.XML
241 | UpgradeLog*.htm
242 | ServiceFabricBackup/
243 | *.rptproj.bak
244 |
245 | # SQL Server files
246 | *.mdf
247 | *.ldf
248 | *.ndf
249 |
250 | # Business Intelligence projects
251 | *.rdl.data
252 | *.bim.layout
253 | *.bim_*.settings
254 | *.rptproj.rsuser
255 |
256 | # Microsoft Fakes
257 | FakesAssemblies/
258 |
259 | # GhostDoc plugin setting file
260 | *.GhostDoc.xml
261 |
262 | # Node.js Tools for Visual Studio
263 | .ntvs_analysis.dat
264 | node_modules/
265 |
266 | # Visual Studio 6 build log
267 | *.plg
268 |
269 | # Visual Studio 6 workspace options file
270 | *.opt
271 |
272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
273 | *.vbw
274 |
275 | # Visual Studio LightSwitch build output
276 | **/*.HTMLClient/GeneratedArtifacts
277 | **/*.DesktopClient/GeneratedArtifacts
278 | **/*.DesktopClient/ModelManifest.xml
279 | **/*.Server/GeneratedArtifacts
280 | **/*.Server/ModelManifest.xml
281 | _Pvt_Extensions
282 |
283 | # Paket dependency manager
284 | .paket/paket.exe
285 | paket-files/
286 |
287 | # FAKE - F# Make
288 | .fake/
289 |
290 | # JetBrains Rider
291 | .idea/
292 | *.sln.iml
293 |
294 | # CodeRush
295 | .cr/
296 |
297 | # Python Tools for Visual Studio (PTVS)
298 | __pycache__/
299 | *.pyc
300 |
301 | # Cake - Uncomment if you are using it
302 | # tools/**
303 | # !tools/packages.config
304 |
305 | # Tabs Studio
306 | *.tss
307 |
308 | # Telerik's JustMock configuration file
309 | *.jmconfig
310 |
311 | # BizTalk build output
312 | *.btp.cs
313 | *.btm.cs
314 | *.odx.cs
315 | *.xsd.cs
316 |
317 | # OpenCover UI analysis results
318 | OpenCover/
319 |
320 | # Azure Stream Analytics local run output
321 | ASALocalRun/
322 |
323 | # MSBuild Binary and Structured Log
324 | *.binlog
325 |
326 | # NVidia Nsight GPU debugger configuration file
327 | *.nvuser
328 |
329 | # MFractors (Xamarin productivity tool) working folder
330 | .mfractor/
331 | nugetCommands.txt
332 |
--------------------------------------------------------------------------------
/IOExtensions/FileTransferManager.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Threading;
4 | using System.Threading.Tasks;
5 |
6 | namespace IOExtensions
7 | {
8 | public enum TransferResult { Success, Failed, Cancelled }
9 |
10 | public static class FileTransferManager
11 | {
12 | public static TransferResult MoveWithProgress(string source, string destination, Action progress, CancellationToken cancellationToken)
13 | {
14 | var startTimestamp = DateTime.Now;
15 | NativeMethods.CopyProgressRoutine lpProgressRoutine = (size, transferred, streamSize, bytesTransferred, number, reason, file, destinationFile, data) =>
16 | {
17 | TransferProgress fileProgress = new TransferProgress(startTimestamp, bytesTransferred)
18 | {
19 | Total = size,
20 | Transferred = transferred,
21 | StreamSize = streamSize,
22 | BytesTransferred = bytesTransferred,
23 | ProcessedFile = source
24 | };
25 | try
26 | {
27 | if (cancellationToken.IsCancellationRequested)
28 | {
29 | return NativeMethods.CopyProgressResult.PROGRESS_CANCEL;
30 | }
31 | progress(fileProgress);
32 | return NativeMethods.CopyProgressResult.PROGRESS_CONTINUE;
33 | }
34 | catch (Exception)
35 | {
36 | return NativeMethods.CopyProgressResult.PROGRESS_STOP;
37 | }
38 | };
39 |
40 | if(cancellationToken.IsCancellationRequested)
41 | {
42 | return TransferResult.Cancelled;
43 | }
44 |
45 | if (!NativeMethods.MoveFileWithProgress(source, destination, lpProgressRoutine, IntPtr.Zero, NativeMethods.MoveFileFlags.MOVE_FILE_REPLACE_EXISTSING | NativeMethods.MoveFileFlags.MOVE_FILE_COPY_ALLOWED | NativeMethods.MoveFileFlags.MOVE_FILE_WRITE_THROUGH))
46 | {
47 | if (cancellationToken.IsCancellationRequested)
48 | {
49 | return TransferResult.Cancelled;
50 | }
51 | return TransferResult.Failed;
52 | }
53 |
54 | return TransferResult.Success;
55 | }
56 |
57 | public static Task MoveWithProgressAsync(string source, string destination, Action progress, CancellationToken cancellationToken)
58 | {
59 | return Task.Run(() =>
60 | {
61 | var destinationPathCorrected = destination;
62 | if (source.IsDirFile() == false)
63 | {
64 | destinationPathCorrected = Helpers.CorrectFileDestinationPath(source, destination);
65 | }
66 | return MoveWithProgress(source, destinationPathCorrected, progress, cancellationToken);
67 | }, cancellationToken);
68 | }
69 |
70 | public static Task CopyWithProgressAsync(string source, string destination, Action progress, bool continueOnFailure, bool copyContentOfDirectory = false)
71 | {
72 | return CopyWithProgressAsync(source, destination, progress, continueOnFailure, CancellationToken.None, copyContentOfDirectory);
73 | }
74 |
75 | public static Task CopyWithProgressAsync(string source, string destination, Action progress, bool continueOnFailure, CancellationToken cancellationToken, bool copyContentOfDirectory = false)
76 | {
77 | return Task.Run(() =>
78 | {
79 | try
80 | {
81 | return CopyWithProgress(source, destination, progress, continueOnFailure, cancellationToken, copyContentOfDirectory);
82 | }
83 | catch
84 | {
85 | return TransferResult.Failed;
86 | }
87 | }, cancellationToken);
88 | }
89 |
90 |
91 | public static TransferResult CopyWithProgress(string source, string destination, Action progress, bool continueOnFailure, bool copyContentOfDirectory = false)
92 | {
93 | return CopyWithProgress(source, destination, progress, continueOnFailure, CancellationToken.None, copyContentOfDirectory);
94 | }
95 |
96 | public static TransferResult CopyWithProgress(string source, string destination, Action progress, bool continueOnFailure, CancellationToken cancellationToken, bool copyContentOfDirectory = false)
97 | {
98 | var isDir = source.IsDirFile();
99 | if (isDir == null)
100 | {
101 | throw new ArgumentException("Source parameter has to be file or directory! " + source);
102 | }
103 | else if (isDir == true)
104 | {
105 | return CopyDirectoryWithProgress(source, destination, progress, continueOnFailure, cancellationToken, copyContentOfDirectory);
106 | }
107 | else
108 | {
109 | if(cancellationToken.IsCancellationRequested)
110 | {
111 | return TransferResult.Cancelled;
112 | }
113 |
114 | var destinationFile = Helpers.CorrectFileDestinationPath(source, destination);
115 |
116 | return CopyFileWithProgress(source, destinationFile, progress, cancellationToken);
117 | }
118 | }
119 |
120 | private static TransferResult CopyDirectoryWithProgress(string sourceDirectory, string destinationDirectory, Action progress, bool continueOnFailure, CancellationToken cancellationToken, bool copyContentOfDirectory)
121 | {
122 | var rootSource = new DirectoryInfo(sourceDirectory.TrimEnd('\\'));
123 | var rootSourceLength = rootSource.FullName.Length;
124 | var rootSourceSize = Helpers.DirSize(rootSource);
125 | long totalTransfered = 0;
126 |
127 | try
128 | {
129 | var destinationNewRootDir = new DirectoryInfo(destinationDirectory.TrimEnd('\\'));
130 | if (!copyContentOfDirectory)
131 | {
132 | destinationNewRootDir = Directory.CreateDirectory(Path.Combine(destinationDirectory, rootSource.Name));
133 | }
134 |
135 | foreach (var directory in rootSource.EnumerateDirectories("*", SearchOption.AllDirectories))
136 | {
137 | if(cancellationToken.IsCancellationRequested)
138 | {
139 | return TransferResult.Cancelled;
140 | }
141 | var newName = directory.FullName.Substring(rootSourceLength+1);
142 | Directory.CreateDirectory(Path.Combine(destinationNewRootDir.FullName, newName));
143 | }
144 |
145 | foreach (var file in rootSource.EnumerateFiles("*", SearchOption.AllDirectories))
146 | {
147 | if (cancellationToken.IsCancellationRequested)
148 | {
149 | return TransferResult.Cancelled;
150 | }
151 |
152 | var newName = file.FullName.Substring(rootSourceLength+1);
153 | var fileCopyStartTimestamp = DateTime.Now;
154 | var result = CopyFileWithProgress(file.FullName, Path.Combine(destinationNewRootDir.FullName, newName), (partialProgress) =>
155 | {
156 | var totalProgress = new TransferProgress(fileCopyStartTimestamp, partialProgress.BytesTransferred)
157 | {
158 | Total = rootSourceSize.Size,
159 | Transferred = totalTransfered + partialProgress.Transferred,
160 | BytesTransferred = totalTransfered + partialProgress.Transferred,
161 | StreamSize = rootSourceSize.Size,
162 | ProcessedFile = file.FullName
163 | };
164 | progress(totalProgress);
165 | }, cancellationToken);
166 |
167 | if (result == TransferResult.Failed && !continueOnFailure)
168 | {
169 | return TransferResult.Failed;
170 | }
171 | else if(result == TransferResult.Cancelled)
172 | {
173 | return TransferResult.Cancelled;
174 | }
175 |
176 | totalTransfered += file.Length;
177 | }
178 | }
179 | catch (Exception)
180 | {
181 | return TransferResult.Failed;
182 | }
183 | return TransferResult.Success;
184 | }
185 |
186 | private static TransferResult CopyFileWithProgress(string sourceFile, string newFile, Action progress, CancellationToken cancellationToken)
187 | {
188 | int pbCancel = 0;
189 | var startTimestamp = DateTime.Now;
190 |
191 | NativeMethods.CopyProgressRoutine lpProgressRoutine = (size, transferred, streamSize, bytesTransferred, number, reason, file, destinationFile, data) =>
192 | {
193 | TransferProgress fileProgress = new TransferProgress(startTimestamp, bytesTransferred)
194 | {
195 | Total = size,
196 | Transferred = transferred,
197 | StreamSize = streamSize,
198 | ProcessedFile = sourceFile
199 | };
200 | try
201 | {
202 | if (cancellationToken.IsCancellationRequested)
203 | {
204 | return NativeMethods.CopyProgressResult.PROGRESS_CANCEL;
205 | }
206 | progress(fileProgress);
207 | return NativeMethods.CopyProgressResult.PROGRESS_CONTINUE;
208 | }
209 | catch (Exception)
210 | {
211 | return NativeMethods.CopyProgressResult.PROGRESS_STOP;
212 | }
213 | };
214 | if(cancellationToken.IsCancellationRequested)
215 | {
216 | return TransferResult.Cancelled;
217 | }
218 |
219 | var ctr = cancellationToken.Register(() => pbCancel = 1);
220 |
221 | var result = NativeMethods.CopyFileEx(sourceFile, newFile, lpProgressRoutine, IntPtr.Zero, ref pbCancel, NativeMethods.CopyFileFlags.COPY_FILE_FAIL_IF_EXISTS);
222 | if(cancellationToken.IsCancellationRequested)
223 | {
224 | return TransferResult.Cancelled;
225 | }
226 |
227 | return result ? TransferResult.Success : TransferResult.Failed;
228 | }
229 | }
230 | }
231 |
--------------------------------------------------------------------------------