diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..7947904 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,394 @@ +############################### +# Core EditorConfig Options # +############################### +root = true + +file_header_template = Copyright (c) by Benjamin Abt (https://schwabencode.com) 2013-2024 All Rights Reserved +charset = utf-8 + +# All files +[*] +indent_style = space + +# XML project files +[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] +indent_size = 4 + +# XML config files +[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] +indent_size = 4 + +# Code files +[*.{cs,csx,vb,vbx}] +indent_size = 4 +insert_final_newline = true +############################### +# .NET Coding Conventions # +############################### +[*.{cs,vb}] +# Organize usings +dotnet_sort_system_directives_first = true +# this. preferences +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_property = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_event = false:silent +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_predefined_type_for_member_access = true:silent +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent +dotnet_style_readonly_field = true:warning +# Expression-level preferences +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_null_propagation = true:warning +dotnet_style_coalesce_expression = true:warning +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_auto_properties = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +############################### +# Naming Conventions # +############################### +# Style Definitions +dotnet_naming_rule.interface_should_be_begins_with_i.severity = warning +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.constant_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constant_should_be_pascal_case.symbols = constant +dotnet_naming_rule.constant_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.private_or_internal_static_field_should_be_static_field.severity = suggestion +dotnet_naming_rule.private_or_internal_static_field_should_be_static_field.symbols = private_or_internal_static_field +dotnet_naming_rule.private_or_internal_static_field_should_be_static_field.style = static_field + +dotnet_naming_rule.private_or_internal_field_should_be_instance_field.severity = suggestion +dotnet_naming_rule.private_or_internal_field_should_be_instance_field.symbols = private_or_internal_field +dotnet_naming_rule.private_or_internal_field_should_be_instance_field.style = instance_field + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.static_field.required_prefix = s_ +dotnet_naming_style.static_field.required_suffix = +dotnet_naming_style.static_field.word_separator = +dotnet_naming_style.static_field.capitalization = camel_case + +dotnet_naming_style.instance_field.required_prefix = _ +dotnet_naming_style.instance_field.required_suffix = +dotnet_naming_style.instance_field.word_separator = +dotnet_naming_style.instance_field.capitalization = camel_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.private_or_internal_field.applicable_kinds = field +dotnet_naming_symbols.private_or_internal_field.applicable_accessibilities = internal, private, private_protected +dotnet_naming_symbols.private_or_internal_field.required_modifiers = + +dotnet_naming_symbols.private_or_internal_static_field.applicable_kinds = field +dotnet_naming_symbols.private_or_internal_static_field.applicable_accessibilities = internal, private, private_protected +dotnet_naming_symbols.private_or_internal_static_field.required_modifiers = static + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +dotnet_naming_symbols.constant.applicable_kinds = field +dotnet_naming_symbols.constant.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.constant.required_modifiers = const + +# Use PascalCase for constant fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style +dotnet_naming_symbols.constant_fields.applicable_kinds = field +dotnet_naming_symbols.constant_fields.applicable_accessibilities = * +dotnet_naming_symbols.constant_fields.required_modifiers = const +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +end_of_line = lf +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_namespace_match_folder = true:suggestion +dotnet_style_allow_multiple_blank_lines_experimental = true:silent +dotnet_style_allow_statement_immediately_after_block_experimental = true:silent +dotnet_code_quality_unused_parameters = all:suggestion +############################### +# C# Coding Conventions # +############################### +[*.cs] +# var preferences +csharp_style_var_for_built_in_types = false:warning +csharp_style_var_when_type_is_apparent = false:warning +csharp_style_var_elsewhere = false:warning +# Expression-bodied members +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +# Pattern matching preferences +csharp_style_pattern_matching_over_is_with_cast_check = true:warning +csharp_style_pattern_matching_over_as_with_null_check = true:warning +# Null-checking preferences +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion +# Modifier preferences +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion +# Expression-level preferences +csharp_prefer_braces = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_prefer_local_over_anonymous_function = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +############################### +# C# Formatting Rules # +############################### +# New line preferences +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true +# Indentation preferences +csharp_indent_case_contents = true +csharp_indent_switch_labels = true +csharp_indent_labels = one_less_than_current +# Space preferences +csharp_space_after_cast = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_around_binary_operators = before_and_after +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +# Wrapping preferences +csharp_preserve_single_line_statements = true +csharp_preserve_single_line_blocks = true +csharp_using_directive_placement = outside_namespace:silent +csharp_prefer_simple_using_statement = true:warning +csharp_style_namespace_declarations = file_scoped:warning +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_top_level_statements = false:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_range_operator = true:silent +csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion +csharp_style_prefer_tuple_swap = true:suggestion +csharp_style_prefer_utf8_string_literals = true:suggestion +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_style_unused_value_expression_statement_preference = discard_variable:silent +csharp_prefer_static_local_function = true:suggestion +csharp_style_prefer_readonly_struct = true:warning +csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent +csharp_style_prefer_switch_expression = true:suggestion +csharp_style_prefer_pattern_matching = true:silent +csharp_style_prefer_not_pattern = true:suggestion +csharp_style_prefer_extended_property_pattern = true:suggestion +csharp_style_prefer_primary_constructors = false:suggestion + +[*.{cs,vb}] +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +#################################################### CA Style + +# CA1050: Types are declared in namespaces to prevent name collisions and as a way to organize related types in an object hierarchy. +dotnet_diagnostic.CA1050.severity = warning + +# CA1507: Use nameof in place of string +dotnet_diagnostic.CA1507.severity = warning + +# CA1825: Avoid unnecessary zero-length array allocations. Use Array.Empty() instead. +dotnet_diagnostic.CA1825.severity = warning + +# CA1850: It is more efficient to use the static 'HashData' method over creating and managing a HashAlgorithm instance to call 'ComputeHash'. +dotnet_diagnostic.CA1850.severity = warning + +# CA1859: Using concrete types avoids virtual or interface call overhead and enables inlining. +dotnet_diagnostic.CA1859.severity = warning + +# CA1860: Prefer using 'IsEmpty', 'Count' or 'Length' properties whichever available, rather than calling 'Enumerable.Any()'. The intent is clearer and it is more performant than using 'Enumerable.Any()' extension method. +dotnet_diagnostic.CA1860.severity = warning + +# CA2211: Static fields that are neither constants nor read-only are not thread-safe. Access to such a field must be carefully controlled and requires advanced programming techniques to synchronize access to the class object. +dotnet_diagnostic.CA2211.severity = silent + +# CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. +dotnet_diagnostic.CS1998.severity = error + +#################################################### IDE Style + +# IDE0039: Use local function +dotnet_diagnostic.IDE0039.severity = silent + +# IDE0060: Avoid unused parameters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names. +dotnet_diagnostic.IDE0060.severity = silent + +# IDE0130: Namespace does not match folder structure +dotnet_diagnostic.IDE0130.severity = warning + +# IDE0270: Expression Null check can be simplified (IDE0029, IDE0030, and IDE0270) +dotnet_diagnostic.IDE0270.severity = none + +# IDE0290: Use primary constructor +dotnet_diagnostic.IDE0290.severity = none +csharp_style_prefer_primary_constructors = false:suggestion + +# IDE0305: Use collection expression for fluent (IDE0305) +dotnet_diagnostic.IDE0305.severity = none + +# IDE1006: Naming rule violation: These words must begin with upper case characters: accessToken +dotnet_diagnostic.IDE1006.severity = warning + +#################################################### RCS Style + +# RCS1021: Codefix Spacing +dotnet_diagnostic.RCS1021.severity = silent + +# RCS1036: Remove unnecessary blank line +dotnet_diagnostic.RCS1036.severity = warning + +# RCS1049: Simplify boolean comparison +# we usually prefer is vs ! +dotnet_diagnostic.RCS1049.severity = silent + +# RCS1073: Convert 'if' to 'return' statement +dotnet_diagnostic.RCS1073.severity = silent + +# RCS1110: Declare 'type' inside namespace +dotnet_diagnostic.RCS1110.severity = warning + +# RCS1163: Unused parameter 'parameter' +dotnet_diagnostic.RCS1163.severity = silent + +# RCS1170: Use read-only auto-implemented property +dotnet_diagnostic.RCS1170.severity = warning + +# RCS1179: Unnecessary assignment +dotnet_diagnostic.RCS1179.severity = warning + +# RCS1194: Implement exception constructors. +dotnet_diagnostic.RCS1194.severity = silent + +# RCS1196: Call extension method as instance method +dotnet_diagnostic.RCS1196.severity = silent + +# RCS1199: Unnecessary null check +dotnet_diagnostic.RCS1199.severity = warning + +# RCS1212: Remove redundant assignment +dotnet_diagnostic.RCS1212.severity = warning + +# RCS1214: Unnecessary interpolated string +dotnet_diagnostic.RCS1214.severity = silent + +# RCS1235: Optimize 'string.Join' call +dotnet_diagnostic.RCS1235.severity = warning + +# RCS1259: Remove empty initializer +dotnet_diagnostic.RCS1259.severity = silent + +# RCS1266: Use raw string literal +dotnet_diagnostic.RCS1266.severity = silent + +#################################################### SYSLIB Style + +# SYSLIB1006: Multiple logging methods are using event id x in class y +dotnet_diagnostic.SYSLIB1006.severity = error + +#################################################### xUnit Style + +# xUnit1048: Support for 'async void' unit tests is being removed from xUnit.net v3. To simplify upgrading, convert the test to 'async Task' instead. +dotnet_diagnostic.xUnit1048.severity = error \ No newline at end of file diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 1ff0c42..0000000 --- a/.gitattributes +++ /dev/null @@ -1,63 +0,0 @@ -############################################################################### -# Set default behavior to automatically normalize line endings. -############################################################################### -* text=auto - -############################################################################### -# Set default behavior for command prompt diff. -# -# This is need for earlier builds of msysgit that does not have it on by -# default for csharp files. -# Note: This is only used by command line -############################################################################### -#*.cs diff=csharp - -############################################################################### -# Set the merge driver for project and solution files -# -# Merging from the command prompt will add diff markers to the files if there -# are conflicts (Merging from VS is not affected by the settings below, in VS -# the diff markers are never inserted). Diff markers may cause the following -# file extensions to fail to load in VS. An alternative would be to treat -# these files as binary and thus will always conflict and require user -# intervention with every merge. To do so, just uncomment the entries below -############################################################################### -#*.sln merge=binary -#*.csproj merge=binary -#*.vbproj merge=binary -#*.vcxproj merge=binary -#*.vcproj merge=binary -#*.dbproj merge=binary -#*.fsproj merge=binary -#*.lsproj merge=binary -#*.wixproj merge=binary -#*.modelproj merge=binary -#*.sqlproj merge=binary -#*.wwaproj merge=binary - -############################################################################### -# behavior for image files -# -# image files are treated as binary by default. -############################################################################### -#*.jpg binary -#*.png binary -#*.gif binary - -############################################################################### -# diff behavior for common document formats -# -# Convert binary document formats to text before diffing them. This feature -# is only available from the command line. Turn it on by uncommenting the -# entries below. -############################################################################### -#*.doc diff=astextplain -#*.DOC diff=astextplain -#*.docx diff=astextplain -#*.DOCX diff=astextplain -#*.dot diff=astextplain -#*.DOT diff=astextplain -#*.pdf diff=astextplain -#*.PDF diff=astextplain -#*.rtf diff=astextplain -#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore index 77cdd86..ce4ea20 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # User-specific files *.suo @@ -15,18 +17,21 @@ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ -[Xx]64/ -[Xx]86/ -[Bb]uild/ +x64/ +x86/ bld/ [Bb]in/ [Oo]bj/ +[Ll]og/ -# Visual Studio 2015 cache/options directory +# Visual Studio 2015/2017 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ +# Visual Studio 2017 auto generated files +Generated\ Files/ + # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* @@ -40,10 +45,19 @@ TestResult.xml [Rr]eleasePS/ dlldata.c -# DNX +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core project.lock.json +project.fragment.lock.json artifacts/ +##**/Properties/launchSettings.json + +# StyleCop +StyleCopReport.xml +# Files built by Visual Studio *_i.c *_p.c *_i.h @@ -81,6 +95,7 @@ ipch/ *.sdf *.cachefile *.VC.db +*.VC.VC.opendb # Visual Studio profiler *.psess @@ -88,6 +103,9 @@ ipch/ *.vspx *.sap +# Visual Studio Trace Files +*.e2e + # TFS 2012 Local Workspace $tf/ @@ -108,6 +126,14 @@ _TeamCity* # DotCover is a Code Coverage Tool *.dotCover +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + # NCrunch _NCrunch_* .*crunch*.local.xml @@ -139,22 +165,25 @@ publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml - -# TODO: Un-comment the next line if you do not want to checkin -# your web deploy settings because they may include unencrypted -# passwords -#*.pubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml *.publishproj +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore -**/packages/* +**/[Pp]ackages/* # except build/, which is used as an MSBuild target. -!**/packages/build/ +!**/[Pp]ackages/build/ # Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config -# NuGet v3's project.json files produces more ignoreable files +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets @@ -166,12 +195,12 @@ csx/ ecf/ rcf/ -# Microsoft Azure ApplicationInsights config file -ApplicationInsights.config - -# Windows Store app package directory +# Windows Store app package directories and files AppPackages/ BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx # Visual Studio cache files # files ending in .cache can be ignored @@ -181,16 +210,23 @@ BundleArtifacts/ # Others ClientBin/ -[Ss]tyle[Cc]op.* ~$* *~ *.dbmdl *.dbproj.schemaview +*.jfm *.pfx *.publishsettings -node_modules/ orleans.codegen.cs +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + # RIA/Silverlight projects Generated_Code/ @@ -201,10 +237,12 @@ _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm +ServiceFabricBackup/ # SQL Server files *.mdf *.ldf +*.ndf # Business Intelligence projects *.rdl.data @@ -219,6 +257,7 @@ FakesAssemblies/ # Node.js Tools for Visual Studio .ntvs_analysis.dat +node_modules/ # Visual Studio 6 build log *.plg @@ -226,6 +265,9 @@ FakesAssemblies/ # Visual Studio 6 workspace options file *.opt +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts @@ -234,13 +276,83 @@ FakesAssemblies/ **/*.Server/ModelManifest.xml _Pvt_Extensions -# LightSwitch generated files -GeneratedArtifacts/ -ModelManifest.xml - # Paket dependency manager .paket/paket.exe +paket-files/ # FAKE - F# Make .fake/ -/_artifacts + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# Local .terraform directories +**/.terraform/* + +# .tfstate files +*.tfstate +*.tfstate.* + +# Crash log files +crash.log + +# Exclude all .tfvars files, which are likely to contain sentitive data, such as +# password, private keys, and other secrets. These should not be part of version +# control as they are data points which are potentially sensitive and subject +# to change depending on the environment. +# +*.tfvars + +# Ignore override files as they are usually used to override resources locally and so +# are not checked in +override.tf +override.tf.json +*_override.tf +*_override.tf.json + +# Include override files you do wish to add to version control using negated pattern +# +# !example_override.tf + +# Include tfplan files to ignore the plan output of command: terraform plan -out=tfplan +# example: *tfplan* + +# Ignore CLI configuration files +.terraformrc +terraform.rc + +# Ignore Live Unit Test config +*.lutconfig diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..ccb44a4 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,68 @@ + + + + Benjamin Abt + Benjamin Abt, SchwabenCode + QuickIO.NET + Benjamin Abt + QuickIO.NET + + QuickIO.NET is an extension to provide faster file operations. To offer you a simple use and an easy integration QuickIO.NET methods lean against the ones provided by .NET. + + en-US + true + embedded + + + + $(MSBuildProjectName.Contains('Test')) + $(MsBuildProjectName.Contains('Benchmark')) + + + + SchwabenCode + SchwabenCode + + + + net7.0-windows;net8.0-windows + $(GlobalNamespacePrefix).$(MSBuildProjectName) + $(GlobalAssemblyNamePrefix).$(MSBuildProjectName) + + + + false + https://github.com/SchwabenCode/QuickIO + true + QuickIO.NET is an extension to provide faster file operations. To offer you a simple use and an easy integration QuickIO.NET methods lean against the ones provided by .NET. + 2.12 + QuickIO, Benjamin Abt, SchwabenCode + false + true + + + + 12.0 + enable + enable + true + + + + + + true + $(MSBuildThisFileDirectory)SchwabenCode.QuickIO.snk + + 0024000004800000940000000602000000240000525341310004000001000100e134c749a752a2 + 42309cd3d12a6407b0329aa45d0e3b647018c42ec1f0e7313bf4993e97234a4c70bc61421750e7 + 84519fec95759fdf35790d9e897abbbb0ca13e094bc2598cc99aad32c720fdbde1abf470be7bca + 833ee99bcc316ecb6cc3f015bffeb1cf6fed735f439c5b13fa0ed4b1a8708f4a02a3fbeaff725a + fa075cd4 + + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..6f78d8a --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,44 @@ + + + true + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + + + all + runtime; build; native; contentfiles; analyzers + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers + + + \ No newline at end of file diff --git a/LICENSE b/LICENSE index 702f33c..3100cbd 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,5 @@ # MIT License -Copyright (c) 2016 Benjamin Abt +Copyright (c) 2013-2024 Benjamin Abt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: diff --git a/NuGet.config b/NuGet.config new file mode 100644 index 0000000..2510e99 --- /dev/null +++ b/NuGet.config @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index dd0c33c..f8b56be 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,12 @@ # QuickIO.NET -**by [SchwabenCode.com](http://www.schwabencode.com) - [Benjamin Abt](http://www.benjamin-abt.com)** +**by [Benjamin Abt](http://www.benjamin-abt.com) - [SchwabenCode.com](http://www.schwabencode.com)** -| Branch | Type | AppVeyor | NuGet Package | -|---|---|---|---| -|master| Stable | [![AppVeyor Stable](https://img.shields.io/appveyor/ci/BenjaminAbt/QuickIO/master.svg?style=flat-square)](https://ci.appveyor.com/project/BenjaminAbt/QuickIO) | [![NuGet](https://img.shields.io/nuget/v/QuickIO.NET.svg?style=flat-square)](https://www.nuget.org/packages/QuickIO.NET) on [NuGet](https://www.nuget.org/packages/QuickIO.NET)| -|develop| Pre Releases | [![AppVeyor Unstable](https://img.shields.io/appveyor/ci/BenjaminAbt/QuickIO/develop.svg?style=flat-square)](https://ci.appveyor.com/project/BenjaminAbt/QuickIO) | [![MyGet](https://img.shields.io/myget/schwabencode/vpre/QuickIO.NET.svg?style=flat-square)](https://www.myget.org/feed/schwabencode/package/nuget/QuickIO.NET) on [MyGet](https://www.myget.org/feed/schwabencode/package/nuget/QuickIO.NET) | +QuickIO is a library that extends and accelerates .NET methods for file operations by not using the .NET abstraction for file operations, but by communicating directly with the Win32 API and avoiding unnecessary early overhead. -# Project Description -QuickIO.NET is an extension for the .NET Framework to provide faster file operations. -To offer you a simple use and an easy integration QuickIO.NET methods lean against the ones provided by the .NET Framework. +## Roadmap + +QuickIO was not developed further for many years, partly due to time constraints and partly in the hope that file operations in .NET would become more efficient. Many workarounds from the .NET Framework 4.0 era are currently included, e.g. asynchronous operations. +Starting in July 2024, the migration to a new codebase has begun. Version 3 will be a transition phase that will only support Windows. Version 4 will then be a cross-platform solution. # Main features * **Much** faster browsing of folder structures (up to 30x faster) @@ -20,8 +18,6 @@ To offer you a simple use and an easy integration QuickIO.NET methods lean again * Calculate **checksums of files and file chunks** * Fully tested source code using UnitTests * Nearly identical signature of methods. So a simple replacement is possible -* **Async** Operations (requires .NET 4.0) -* Multiple releases from .NET 2.0 to .NET 4.5 ## Give Thanks It took many hours to create this library in its published form. @@ -30,43 +26,22 @@ If you like the library and saved you much time, then maybe respect this with a It would be also very nice when you just write me, if you like this implementation and tell me what you've started! ## License - MIT License - - Copyright (c) 2016 Benjamin Abt - - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -# Releases - -## Stable on NuGet -We publish stable releases to NuGet. - - Install-Package QuickIO.NET -See [QuickIO.NET on NuGet](https://www.nuget.org/packages/QuickIO.NET/) - -## Pre on MyGet - -Use our [SchwabenCode Development feed](https://www.myget.org/gallery/schwabencode) `https://www.myget.org/F/schwabencode/api/v3/index.json` on [MyGet](https://www.myget.org/gallery/schwabencode) for unstable releases. - - Install-Package QuickIO.NET -Pre - -See [QuickIO.NET on MyGet](https://www.myget.org/feed/schwabencode/package/nuget/QuickIO.NET) - -## Branches -- [master](https://github.com/SchwabenCode/QuickIO/tree/master): stable -- [develop](https://github.com/SchwabenCode/QuickIO/tree/develop): used during development - -## Contributors -I want to say thank you to following contributors -- [Avinash Puchalapalli](https://github.com/holycrepe) +> MIT License +> Copyright (c) 2013-2024 Benjamin Abt +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## Remarks This library was created on the basis of my own needs. I am not responsible for integration issues, errors or any damage. On usage problems, please use public forums. For bugs and features please fork to your own branch, fix it and create a pull request or use the [issue tab](https://github.com/SchwabenCode/QuickIO/issues). Thank you and good luck with your software. + +## History + +QuickIO was initially developed on CodePlex and migrated to GitHub in 2016 after CodePlex was discontinued. During the migration, as it later turned out, not all of the history was transferred; however, since CodePlex no longer exists, the history is lost. \ No newline at end of file diff --git a/SchwabenCode.QuickIO.nuspec b/SchwabenCode.QuickIO.nuspec deleted file mode 100644 index d787f97..0000000 --- a/SchwabenCode.QuickIO.nuspec +++ /dev/null @@ -1,21 +0,0 @@ - - - - QuickIO.NET - $version$ - Benjamin Abt (www.SCHWABENCODE.com) - Benjamin Abt 2016 (www.SCHWABENCODE.com) - https://github.com/SchwabenCode/QuickIO/blob/master/LICENSE - false - http://quickio.net - QuickIO.NET is an extension for the .NET Framework to offer faster file operations. - - - - - - - - - - \ No newline at end of file diff --git a/SchwabenCode.QuickIO.sln b/SchwabenCode.QuickIO.sln index d60180e..66310a8 100644 --- a/SchwabenCode.QuickIO.sln +++ b/SchwabenCode.QuickIO.sln @@ -1,25 +1,30 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 +# Visual Studio Version 17 +VisualStudioVersion = 17.11.35208.52 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SchwabenCode.QuickIO", "src\SchwabenCode.QuickIO\SchwabenCode.QuickIO.csproj", "{B33DBCEE-42F4-4570-B4EF-5412CE4A4BDA}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QuickIO", "src\QuickIO\QuickIO.csproj", "{435893FD-03CF-460F-B7DC-A18FEC7526A7}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{ABD069AB-F231-4181-9D07-C896D09788A9}" - ProjectSection(SolutionItems) = preProject - appveyor.yml = appveyor.yml - LICENSE = LICENSE - README.md = README.md - SchwabenCode.QuickIO.nuspec = SchwabenCode.QuickIO.nuspec - EndProjectSection +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QuickIO.IntegrationTests", "tests\QuickIO.IntegrationTests\QuickIO.IntegrationTests.csproj", "{7E7A00FE-15A7-434E-8AEB-553DF26FF0A4}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{F71A44C3-0AB3-4854-971E-2F4021F7C2E2}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QuickIO.UnitTests", "tests\QuickIO.UnitTests\QuickIO.UnitTests.csproj", "{755CFD84-D67D-48FA-AF91-BB45ADFF6489}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{66095698-080C-4938-8F62-D4C470EEBB97}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{F5111071-EFEB-49A9-B17F-388541B168CA}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SchwabenCode.QuickIO.UnitTests", "test\SchwabenCode.QuickIO.UnitTests\SchwabenCode.QuickIO.UnitTests.csproj", "{4867DD64-C401-4139-84F7-4252E138CC9B}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{B206207E-EEC5-4F1B-BDF5-1D225EF10679}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SchwabenCode.QuickIO.IntegrationTests", "test\SchwabenCode.QuickIO.IntegrationTests\SchwabenCode.QuickIO.IntegrationTests.csproj", "{84664F86-61B1-4970-B390-4FCD71A8C081}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_", "_", "{B8A157F1-0014-4125-824F-D476951DC63A}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + .gitignore = .gitignore + Directory.Build.props = Directory.Build.props + Directory.Packages.props = Directory.Packages.props + global.json = global.json + LICENSE = LICENSE + NuGet.config = NuGet.config + README.md = README.md + version.json = version.json + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -27,25 +32,28 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {B33DBCEE-42F4-4570-B4EF-5412CE4A4BDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B33DBCEE-42F4-4570-B4EF-5412CE4A4BDA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B33DBCEE-42F4-4570-B4EF-5412CE4A4BDA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B33DBCEE-42F4-4570-B4EF-5412CE4A4BDA}.Release|Any CPU.Build.0 = Release|Any CPU - {4867DD64-C401-4139-84F7-4252E138CC9B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4867DD64-C401-4139-84F7-4252E138CC9B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4867DD64-C401-4139-84F7-4252E138CC9B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4867DD64-C401-4139-84F7-4252E138CC9B}.Release|Any CPU.Build.0 = Release|Any CPU - {84664F86-61B1-4970-B390-4FCD71A8C081}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {84664F86-61B1-4970-B390-4FCD71A8C081}.Debug|Any CPU.Build.0 = Debug|Any CPU - {84664F86-61B1-4970-B390-4FCD71A8C081}.Release|Any CPU.ActiveCfg = Release|Any CPU - {84664F86-61B1-4970-B390-4FCD71A8C081}.Release|Any CPU.Build.0 = Release|Any CPU + {435893FD-03CF-460F-B7DC-A18FEC7526A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {435893FD-03CF-460F-B7DC-A18FEC7526A7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {435893FD-03CF-460F-B7DC-A18FEC7526A7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {435893FD-03CF-460F-B7DC-A18FEC7526A7}.Release|Any CPU.Build.0 = Release|Any CPU + {7E7A00FE-15A7-434E-8AEB-553DF26FF0A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7E7A00FE-15A7-434E-8AEB-553DF26FF0A4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7E7A00FE-15A7-434E-8AEB-553DF26FF0A4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7E7A00FE-15A7-434E-8AEB-553DF26FF0A4}.Release|Any CPU.Build.0 = Release|Any CPU + {755CFD84-D67D-48FA-AF91-BB45ADFF6489}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {755CFD84-D67D-48FA-AF91-BB45ADFF6489}.Debug|Any CPU.Build.0 = Debug|Any CPU + {755CFD84-D67D-48FA-AF91-BB45ADFF6489}.Release|Any CPU.ActiveCfg = Release|Any CPU + {755CFD84-D67D-48FA-AF91-BB45ADFF6489}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {B33DBCEE-42F4-4570-B4EF-5412CE4A4BDA} = {F71A44C3-0AB3-4854-971E-2F4021F7C2E2} - {4867DD64-C401-4139-84F7-4252E138CC9B} = {66095698-080C-4938-8F62-D4C470EEBB97} - {84664F86-61B1-4970-B390-4FCD71A8C081} = {66095698-080C-4938-8F62-D4C470EEBB97} + {435893FD-03CF-460F-B7DC-A18FEC7526A7} = {F5111071-EFEB-49A9-B17F-388541B168CA} + {7E7A00FE-15A7-434E-8AEB-553DF26FF0A4} = {B206207E-EEC5-4F1B-BDF5-1D225EF10679} + {755CFD84-D67D-48FA-AF91-BB45ADFF6489} = {B206207E-EEC5-4F1B-BDF5-1D225EF10679} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {6829A37E-1842-4B1C-94AE-BB5EC9DC0905} EndGlobalSection EndGlobal diff --git a/SchwabenCode.QuickIO.snk b/SchwabenCode.QuickIO.snk new file mode 100644 index 0000000..a91d0fd Binary files /dev/null and b/SchwabenCode.QuickIO.snk differ diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index bac6add..0000000 --- a/appveyor.yml +++ /dev/null @@ -1,130 +0,0 @@ -# develop branch commits: build, test and deploy on MyGet as pre-release -# master branch commits without tag: no deploy, just build and test -# master branch commits with tag (GitHub release): build, test and deploy on Nuget as stable -- - branches: - only: - - develop - - version: 2.10.{build} - - environment: - packageVersion: $env:buildVersion - - init: - - ps: | - $version = new-object System.Version $env:APPVEYOR_BUILD_VERSION - $env:PackageVersion = "{0}.{1}.{2}-beta" -f $version.Major, $version.Minor, $version.Build - - assembly_info: - patch: true - file: '**\AssemblyInfo.*' - assembly_version: '$(APPVEYOR_BUILD_VERSION)' - assembly_file_version: '$(APPVEYOR_BUILD_VERSION)' - assembly_informational_version: '$(PackageVersion)' - - configuration: Release - - nuget: - account_feed: true - project_feed: true - disable_publish_on_pr: true - - - before_build: - - nuget restore - - build: - verbosity: minimal - project: SchwabenCode.QuickIO.sln - - after_build: - - ps: nuget pack SchwabenCode.QuickIO.nuspec -version "$env:PackageVersion" - - test: - assemblies: - - 'test\**\*.UnitTests.dll' - - 'test\**\*.IntegrationTests.dll' - - artifacts: - - path: 'QuickIO.NET.*.nupkg' - name: SchwabenCode.QuickIO-NuGetPackage - - deploy: - - provider: NuGet - server: https://www.myget.org/F/schwabencode/api/v2/package - api_key: - secure: 5r4u1BFGZ9CjakS0ATOT2sAKcOjJ7BHzRYJC88aQnYOplsCsKYVtwcTEIGNzHOdh - artifact: SchwabenCode.QuickIO-NuGetPackage - -- - branches: - only: - - master - - version: 2.10.{build} - - environment: - packageVersion: $env:buildVersion - - init: - - ps: | - $version = new-object System.Version $env:APPVEYOR_BUILD_VERSION - $env:PackageVersion = "{0}.{1}.{2}" -f $version.Major, $version.Minor, $version.Build - - assembly_info: - patch: true - file: '**\AssemblyInfo.*' - assembly_version: '$(APPVEYOR_BUILD_VERSION)' - assembly_file_version: '$(APPVEYOR_BUILD_VERSION)' - assembly_informational_version: '$(PackageVersion)' - - configuration: Release - - nuget: - account_feed: true - project_feed: true - disable_publish_on_pr: true - - - before_build: - - nuget restore - - build: - verbosity: minimal - project: SchwabenCode.QuickIO.sln - - test: - assemblies: - - 'tests\**\*.UnitTests.dll' - - 'tests\***\*.IntegrationTests.dll' - - after_build: - - ps: nuget pack SchwabenCode.QuickIO.nuspec -version "$env:PackageVersion" - - artifacts: - - path: 'QuickIO.NET.*.nupkg' - name: SchwabenCode.QuickIO-NuGetPackage - - deploy: - - provider: NuGet - api_key: - secure: 1A6ODONpTd1O0+/7ojwfX8H1aAto/Wvqb9RdKg2oKk/FDaKedTXXi9azFBxumdku - artifact: SchwabenCode.QuickIO-NuGetPackage - on: - branch: master - appveyor_repo_tag: true - -# all other branches -# compile, test -- - version: 2.10.{build} - - configuration: Release - - before_build: - - nuget restore - - build: - verbosity: minimal - project: SchwabenCode.QuickIO.sln diff --git a/global.json b/global.json new file mode 100644 index 0000000..dab9599 --- /dev/null +++ b/global.json @@ -0,0 +1,6 @@ +{ + "sdk": { + "version": "9.0.100-preview.6" + } + } + \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/SaveOutput.cs b/src/QuickIO/CodeTemplates/SaveOutput.cs similarity index 100% rename from src/SchwabenCode.QuickIO/_CodeGeneration/Templates/SaveOutput.cs rename to src/QuickIO/CodeTemplates/SaveOutput.cs diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/SaveOutput.tt b/src/QuickIO/CodeTemplates/SaveOutput.tt similarity index 100% rename from src/SchwabenCode.QuickIO/_CodeGeneration/Templates/SaveOutput.tt rename to src/QuickIO/CodeTemplates/SaveOutput.tt diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticAttributeMethods.cs b/src/QuickIO/CodeTemplates/StaticAttributeMethods.cs similarity index 100% rename from src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticAttributeMethods.cs rename to src/QuickIO/CodeTemplates/StaticAttributeMethods.cs diff --git a/src/QuickIO/CodeTemplates/StaticAttributeMethods.tt b/src/QuickIO/CodeTemplates/StaticAttributeMethods.tt new file mode 100644 index 0000000..77d7439 --- /dev/null +++ b/src/QuickIO/CodeTemplates/StaticAttributeMethods.tt @@ -0,0 +1,145 @@ +<#+ +void Generate(string className) +{ + + #> +using System; +using System.IO; +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public partial class <#= className #> +{ + /// + /// Gets the of the directory or file. + /// + /// The path to the directory or file. + /// New attributes to set. + /// The of the directory or file. + public static void SetAttributes( string path , FileAttributes attributes ) + { + SetAttributes( new QuickIOPathInfo( path ), attributes ); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// New attributes to set. + /// The of the directory or file. + public static void SetAttributes( QuickIOPathInfo info, FileAttributes attributes ) + { + InternalQuickIO.SetAttributes( info, attributes); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// New attributes to set. + /// The of the directory or file. + public static void SetAttributes( <#= className #>Info info, FileAttributes attributes ) + { + InternalQuickIO.SetAttributes( info.PathInfo, attributes); + } + + /// + /// Gets the of the directory or file. + /// + /// The path to the directory or file. + /// The of the directory or file. + public static FileAttributes GetAttributes( string path ) + { + return GetAttributes( new QuickIOPathInfo( path ) ); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// The of the directory or file. + public static FileAttributes GetAttributes( QuickIOPathInfo info ) + { + return InternalQuickIO.GetAttributes( info ); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// The of the directory or file. + public static FileAttributes GetAttributes( <#=className#>Info info ) + { + return InternalQuickIO.GetAttributes( info.PathInfo ); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static bool RemoveAttribute( string path, FileAttributes attribute ) + { + return RemoveAttribute( new QuickIOPathInfo( path ), attribute ); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static bool RemoveAttribute( QuickIOPathInfo info, FileAttributes attribute) + { + return InternalQuickIO.RemoveAttribute( info, attribute ); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static bool RemoveAttribute( <#=className#>Info info, FileAttributes attribute ) + { + return InternalQuickIO.RemoveAttribute( info.PathInfo, attribute ); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static bool AddAttribute( string path, FileAttributes attribute ) + { + return AddAttribute( new QuickIOPathInfo( path ), attribute ); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static bool AddAttribute( QuickIOPathInfo info, FileAttributes attribute ) + { + return InternalQuickIO.AddAttribute( info, attribute ); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static bool AddAttribute( <#=className#>Info info, FileAttributes attribute ) + { + return InternalQuickIO.AddAttribute( info.PathInfo, attribute ); + } +} +<#+ +} +#> diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticFileTimeMethods.cs b/src/QuickIO/CodeTemplates/StaticAttributeMethods_Async.cs similarity index 100% rename from src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticFileTimeMethods.cs rename to src/QuickIO/CodeTemplates/StaticAttributeMethods_Async.cs diff --git a/src/QuickIO/CodeTemplates/StaticAttributeMethods_Async.tt b/src/QuickIO/CodeTemplates/StaticAttributeMethods_Async.tt new file mode 100644 index 0000000..f484e2f --- /dev/null +++ b/src/QuickIO/CodeTemplates/StaticAttributeMethods_Async.tt @@ -0,0 +1,145 @@ +<#+ +void Generate(string className) +{ + + #> +using System.Threading.Tasks; +using SchwabenCode.QuickIO.Compatibility; +using System.IO; + +namespace SchwabenCode.QuickIO; + +public partial class <#= className #> +{ + /// + /// Gets the of the directory or file. + /// + /// The path to the directory or file. + /// New attributes to set. + /// The of the directory or file. + public static Task SetAttributesAsync( string path, FileAttributes attributes ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( ( ) => <#= className #>.SetAttributes( path, attributes ) ); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// New attributes to set. + /// The of the directory or file. + public static Task SetAttributesAsync( QuickIOPathInfo info, FileAttributes attributes ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( ( ) => <#= className #>.SetAttributes( info, attributes) ); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// New attributes to set. + /// The of the directory or file. + public static Task SetAttributesAsync( <#= className #>Info info, FileAttributes attributes ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( ( ) => <#= className #>.SetAttributes( info.PathInfo, attributes) ); + } + + /// + /// Gets the of the directory or file. + /// + /// The path to the directory or file. + /// The of the directory or file. + public static Task GetAttributesAsync( string path ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( ( ) => <#= className #>.GetAttributes( path ) ); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// The of the directory or file. + public static Task GetAttributesAsync( QuickIOPathInfo info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( ( ) => <#= className #>.GetAttributes( info ) ); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// The of the directory or file. + public static Task GetAttributesAsync( <#=className#>Info info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( ( ) => <#= className #>.GetAttributes( info ) ); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static Task RemoveAttributeAsync( string path, FileAttributes attribute ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( ( ) => <#= className #>.RemoveAttribute( path, attribute ) ); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static Task RemoveAttributeAsync( QuickIOPathInfo info, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( ( ) => <#= className #>.RemoveAttribute( info, attribute ) ); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static Task RemoveAttributeAsync( <#=className#>Info info, FileAttributes attribute ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( ( ) => <#= className #>.RemoveAttribute( info, attribute ) ); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static Task AddAttributeAsync( string path, FileAttributes attribute ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( ( ) => <#= className #>.AddAttribute( path, attribute ) ); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static Task AddAttributeAsync( QuickIOPathInfo info, FileAttributes attribute ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( ( ) => <#= className #>.AddAttribute( info, attribute ) ); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static Task AddAttributeAsync( <#=className#>Info info, FileAttributes attribute ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( ( ) => <#= className #>.AddAttribute( info, attribute ) ); + } +} +<#+ +} +#> diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticRootMethods.cs b/src/QuickIO/CodeTemplates/StaticFileTimeMethods.cs similarity index 100% rename from src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticRootMethods.cs rename to src/QuickIO/CodeTemplates/StaticFileTimeMethods.cs diff --git a/src/QuickIO/CodeTemplates/StaticFileTimeMethods.tt b/src/QuickIO/CodeTemplates/StaticFileTimeMethods.tt new file mode 100644 index 0000000..92e359d --- /dev/null +++ b/src/QuickIO/CodeTemplates/StaticFileTimeMethods.tt @@ -0,0 +1,473 @@ +<#+ +void Generate(string className) +{ + +var pathPassValueText = "Affected file or directory"; +var dateTimePassValueText = "The time that is to be used"; +var dateTimeReturnValueText = "A structure."; + + #> +using System; +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public partial class <#= className #> +{ + /// + /// Returns the creation time of the file or directory + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTime( String path ) + { + return GetCreationTimeUtc( path ).ToLocalTime( ); + } + /// + /// Returns the creation time of the file or directory + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTime( QuickIOPathInfo info ) + { + return GetCreationTimeUtc( info ).ToLocalTime( ); + } + /// + /// Returns the creation time of the file or directory + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTime( <#= className #>Info info ) + { + return GetCreationTimeUtc( info.PathInfo ).ToLocalTime( ); + } + + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTimeUtc( String path ) + { + return GetCreationTimeUtc( new QuickIOPathInfo( path ) ); + } + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTimeUtc( QuickIOPathInfo info ) + { + return info.FindData.GetCreationTimeUtc( ); + } + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime? GetCreationTimeUtc( <#= className #>Info info ) + { + return info.FindData?.GetCreationTimeUtc( ); + } + + /// + /// Returns the time of last access of the file or directory + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTime( String path ) + { + return GetLastAccessTimeUtc( path ).ToLocalTime( ); + } + /// + /// Returns the time of last access of the file or directory + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTime( QuickIOPathInfo info ) + { + return GetLastAccessTimeUtc( info ).ToLocalTime( ); + } + /// + /// Returns the time of last access of the file or directory + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTime( <#= className #>Info info ) + { + return GetLastAccessTimeUtc( info.PathInfo ).ToLocalTime( ); + } + + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTimeUtc( String path ) + { + return GetLastAccessTimeUtc( new QuickIOPathInfo( path ) ); + } + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTimeUtc( QuickIOPathInfo info ) + { + return info.FindData.GetLastAccessTimeUtc( ); + } + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime? GetLastAccessTimeUtc( <#= className #>Info info ) + { + return info.FindData?.GetLastAccessTimeUtc( ); + } + + /// + /// Returns the time of the file or directory was last written + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTime( String path ) + { + return GetLastWriteTimeUtc( path ).ToLocalTime( ); + } + /// + /// Returns the time of the file or directory was last written + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTime( QuickIOPathInfo info ) + { + return GetLastWriteTimeUtc( info ).ToLocalTime( ); + } + /// + /// Returns the time of the file or directory was last written + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTime( <#= className #>Info info ) + { + return GetLastWriteTimeUtc( info.PathInfo ).ToLocalTime( ); + } + + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTimeUtc( String path ) + { + return GetLastWriteTimeUtc( new QuickIOPathInfo( path ) ); + } + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTimeUtc( QuickIOPathInfo info ) + { + return info.FindData.GetLastWriteTimeUtc( ); + } + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime? GetLastWriteTimeUtc( <#= className #>Info info ) + { + return info.FindData?.GetLastWriteTimeUtc( ); + } + + /// + /// Sets the time the file was created. + /// + /// <#= pathPassValueText #> + /// <#= dateTimePassValueText #> + /// <#= dateTimePassValueText #> + /// <#= dateTimePassValueText #> + public static void SetAllFileTimes( String path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) + { + SetAllFileTimesUtc( path, creationTime.ToUniversalTime( ), lastAccessTime.ToUniversalTime( ), lastWriteTime.ToUniversalTime( ) ); + } + /// + /// Sets the time the file was created. + /// + /// <#= pathPassValueText #> + /// <#= dateTimePassValueText #> + /// <#= dateTimePassValueText #> + /// <#= dateTimePassValueText #> + public static void SetAllFileTimes( QuickIOPathInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) + { + SetAllFileTimesUtc( info, creationTime.ToUniversalTime( ), lastAccessTime.ToUniversalTime( ), lastWriteTime.ToUniversalTime( ) ); + } + /// + /// Sets the time the file was created. + /// + /// <#= pathPassValueText #> + /// <#= dateTimePassValueText #> + /// <#= dateTimePassValueText #> + /// <#= dateTimePassValueText #> + public static void SetAllFileTimes( <#= className #>Info info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) + { + SetAllFileTimesUtc( info, creationTime.ToUniversalTime( ), lastAccessTime.ToUniversalTime( ), lastWriteTime.ToUniversalTime( ) ); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// <#= pathPassValueText #> + /// <#= dateTimePassValueText #> (UTC) + /// <#= dateTimePassValueText #> (UTC) + /// <#= dateTimePassValueText #> (UTC) + public static void SetAllFileTimesUtc( String path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) + { + InternalQuickIO.SetAllFileTimes( new QuickIOPathInfo( path ), creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// <#= pathPassValueText #> + /// <#= dateTimePassValueText #> (UTC) + /// <#= dateTimePassValueText #> (UTC) + /// <#= dateTimePassValueText #> (UTC) + public static void SetAllFileTimesUtc( QuickIOPathInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) + { + InternalQuickIO.SetAllFileTimes( info, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// <#= pathPassValueText #> + /// <#= dateTimePassValueText #> (UTC) + /// <#= dateTimePassValueText #> (UTC) + /// <#= dateTimePassValueText #> (UTC) + public static void SetAllFileTimesUtc( <#= className #>Info info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) + { + InternalQuickIO.SetAllFileTimes( info.PathInfo, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ); + } + + /// + /// Defines the time at which the file or directory was created + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetCreationTime( String path, DateTime creationTime ) + { + SetCreationTimeUtc( path, creationTime.ToUniversalTime( ) ); + } + /// + /// Defines the time at which the file or directory was created + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetCreationTime( QuickIOPathInfo info, DateTime creationTime ) + { + SetCreationTimeUtc( info, creationTime.ToUniversalTime( ) ); + } + /// + /// Defines the time at which the file or directory was created + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetCreationTime( <#= className #>Info info, DateTime creationTime ) + { + SetCreationTimeUtc( info, creationTime.ToUniversalTime( ) ); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static void SetCreationTimeUtc( String path, DateTime creationTimeUtc ) + { + InternalQuickIO.SetCreationTimeUtc( new QuickIOPathInfo( path ), creationTimeUtc ); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static void SetCreationTimeUtc( QuickIOPathInfo info, DateTime creationTimeUtc ) + { + InternalQuickIO.SetCreationTimeUtc( info, creationTimeUtc ); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static void SetCreationTimeUtc( <#= className #>Info info, DateTime creationTimeUtc ) + { + InternalQuickIO.SetCreationTimeUtc( info.PathInfo, creationTimeUtc ); + } + + /// + /// Defines the time at which the file or directory was last accessed + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetLastAccessTime( String path, DateTime lastAccessTime ) + { + SetLastAccessTimeUtc( path, lastAccessTime.ToUniversalTime( ) ); + } + /// + /// Defines the time at which the file or directory was last accessed + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx + public static void SetLastAccessTime( QuickIOPathInfo info, DateTime lastAccessTime ) + { + SetLastAccessTimeUtc( info, lastAccessTime.ToUniversalTime( ) ); + } + /// + /// Defines the time at which the file or directory was last accessed + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx + public static void SetLastAccessTime( <#= className #>Info info, DateTime lastAccessTime ) + { + SetLastAccessTimeUtc( info, lastAccessTime.ToUniversalTime( ) ); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static void SetLastAccessTimeUtc( String path, DateTime lastAccessTimeUtc ) + { + InternalQuickIO.SetLastAccessTimeUtc( new QuickIOPathInfo( path ), lastAccessTimeUtc ); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static void SetLastAccessTimeUtc( QuickIOPathInfo info, DateTime lastAccessTimeUtc ) + { + InternalQuickIO.SetLastAccessTimeUtc( info, lastAccessTimeUtc ); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static void SetLastAccessTimeUtc( <#= className #>Info info, DateTime lastAccessTimeUtc ) + { + InternalQuickIO.SetLastAccessTimeUtc( info.PathInfo, lastAccessTimeUtc ); + } + + /// + /// Defines the time at which the file or directory was last written + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetLastWriteTime( String path, DateTime lastWriteTime ) + { + SetLastWriteTimeUtc( path, lastWriteTime.ToUniversalTime( ) ); + } + /// + /// Defines the time at which the file or directory was last written + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx + public static void SetLastWriteTime( QuickIOPathInfo info, DateTime lastWriteTime ) + { + SetLastWriteTimeUtc( info, lastWriteTime.ToUniversalTime( ) ); + } + /// + /// Defines the time at which the file or directory was last written + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx + public static void SetLastWriteTime( <#= className #>Info info, DateTime lastWriteTime ) + { + SetLastWriteTimeUtc( info, lastWriteTime.ToUniversalTime( ) ); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static void SetLastWriteTimeUtc( String path, DateTime lastWriteTimeUtc ) + { + InternalQuickIO.SetLastWriteTimeUtc( new QuickIOPathInfo( path ), lastWriteTimeUtc ); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static void SetLastWriteTimeUtc( QuickIOPathInfo info, DateTime lastWriteTimeUtc ) + { + InternalQuickIO.SetLastWriteTimeUtc( info, lastWriteTimeUtc ); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static void SetLastWriteTimeUtc( <#= className #>Info info, DateTime lastWriteTimeUtc ) + { + InternalQuickIO.SetLastWriteTimeUtc( info.PathInfo, lastWriteTimeUtc ); + } +} +<#+ + } +#> diff --git a/test/SchwabenCode.QuickIO.IntegrationTests/_TestFolders/ExistingFolder/OneTextFileHere.txt b/src/QuickIO/CodeTemplates/StaticFileTimeMethods_Async.cs similarity index 100% rename from test/SchwabenCode.QuickIO.IntegrationTests/_TestFolders/ExistingFolder/OneTextFileHere.txt rename to src/QuickIO/CodeTemplates/StaticFileTimeMethods_Async.cs diff --git a/src/QuickIO/CodeTemplates/StaticFileTimeMethods_Async.tt b/src/QuickIO/CodeTemplates/StaticFileTimeMethods_Async.tt new file mode 100644 index 0000000..fabab13 --- /dev/null +++ b/src/QuickIO/CodeTemplates/StaticFileTimeMethods_Async.tt @@ -0,0 +1,474 @@ +<#+ +void Generate(string className) +{ + +var pathPassValueText = "Affected file or directory"; +var dateTimePassValueText = "The time that is to be used"; +var dateTimeReturnValueText = "A structure."; + + #> +using System; +using System.Threading.Tasks; +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class <#= className #> +{ + /// + /// Returns the creation time of the file or directory + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeAsync( string path ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetCreationTime( path ) ); + } + /// + /// Returns the creation time of the file or directory + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeAsync( QuickIOPathInfo info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetCreationTime( info ) ); + } + /// + /// Returns the creation time of the file or directory + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeAsync( <#= className #>Info info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetCreationTime( info ) ); + } + + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeUtcAsync( string path ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetCreationTimeUtc( path ) ); + } + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeUtcAsync( QuickIOPathInfo info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetCreationTimeUtc( info ) ); + } + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeUtcAsync( <#= className #>Info info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetCreationTimeUtc( info ) ); + } + + /// + /// Returns the time of last access of the file or directory + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeAsync( string path ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetLastAccessTime( path ) ); + } + /// + /// Returns the time of last access of the file or directory + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeAsync( QuickIOPathInfo info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetLastAccessTime( info ) ); + } + /// + /// Returns the time of last access of the file or directory + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeAsync( <#= className #>Info info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetLastAccessTime( info ) ); + } + + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeUtcAsync( string path ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetLastAccessTimeUtc( path ) ); + } + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeUtcAsync( QuickIOPathInfo info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetLastAccessTimeUtc( info ) ); + } + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeUtcAsync( <#= className #>Info info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetLastAccessTimeUtc( info ) ); + } + + /// + /// Returns the time of the file or directory was last written + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeAsync( string path ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetLastAccessTimeUtc( path ) ); + } + /// + /// Returns the time of the file or directory was last written + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeAsync( QuickIOPathInfo info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetLastAccessTimeUtc( info ) ); + } + /// + /// Returns the time of the file or directory was last written + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeAsync( <#= className #>Info info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetLastAccessTimeUtc( info ) ); + } + + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeUtcAsync( string path ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetLastWriteTimeUtc( path ) ); + } + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeUtcAsync( QuickIOPathInfo info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetLastWriteTimeUtc( info ) ); + } + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// <#= pathPassValueText #> + /// <#= dateTimeReturnValueText #> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeUtcAsync( <#= className #>Info info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( () => <#= className #>.GetLastWriteTimeUtc( info ) ); + } + + /// + /// Sets the time the file was created. + /// + /// <#= pathPassValueText #> + /// <#= dateTimePassValueText #> + /// <#= dateTimePassValueText #> + /// <#= dateTimePassValueText #> + public static Task SetAllFileTimesAsync( string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetAllFileTimes( path, creationTime, lastAccessTime, lastWriteTime ) ); + } + /// + /// Sets the time the file was created. + /// + /// <#= pathPassValueText #> + /// <#= dateTimePassValueText #> + /// <#= dateTimePassValueText #> + /// <#= dateTimePassValueText #> + public static Task SetAllFileTimesAsync( QuickIOPathInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetAllFileTimes( info, creationTime, lastAccessTime, lastWriteTime ) ); + } + /// + /// Sets the time the file was created. + /// + /// <#= pathPassValueText #> + /// <#= dateTimePassValueText #> + /// <#= dateTimePassValueText #> + /// <#= dateTimePassValueText #> + public static Task SetAllFileTimesAsync( <#= className #>Info info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetAllFileTimes( info, creationTime, lastAccessTime, lastWriteTime ) ); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// <#= pathPassValueText #> + /// <#= dateTimePassValueText #> (UTC) + /// <#= dateTimePassValueText #> (UTC) + /// <#= dateTimePassValueText #> (UTC) + public static Task SetAllFileTimesUtcAsync( string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetAllFileTimesUtc( path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ) ); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// <#= pathPassValueText #> + /// <#= dateTimePassValueText #> (UTC) + /// <#= dateTimePassValueText #> (UTC) + /// <#= dateTimePassValueText #> (UTC) + public static Task SetAllFileTimesUtcAsync( QuickIOPathInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetAllFileTimesUtc( info, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ) ); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// <#= pathPassValueText #> + /// <#= dateTimePassValueText #> (UTC) + /// <#= dateTimePassValueText #> (UTC) + /// <#= dateTimePassValueText #> (UTC) + public static Task SetAllFileTimesUtcAsync( <#= className #>Info info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetAllFileTimesUtc( info, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ) ); + } + + /// + /// Defines the time at which the file or directory was created + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetCreationTimeAsync( string path, DateTime creationTime ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetCreationTime( path, creationTime ) ); + } + /// + /// Defines the time at which the file or directory was created + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetCreationTimeAsync( QuickIOPathInfo info, DateTime creationTime ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetCreationTime( info, creationTime ) ); + } + /// + /// Defines the time at which the file or directory was created + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetCreationTimeAsync( <#= className #>Info info, DateTime creationTime ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetCreationTime( info, creationTime ) ); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static Task SetCreationTimeUtcAsync( string path, DateTime creationTimeUtc ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetCreationTimeUtc( path, creationTimeUtc ) ); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static Task SetCreationTimeUtcAsync( QuickIOPathInfo info, DateTime creationTimeUtc ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetCreationTimeUtc( info, creationTimeUtc ) ); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static Task SetCreationTimeUtcAsync( <#= className #>Info info, DateTime creationTimeUtc ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetCreationTimeUtc( info, creationTimeUtc ) ); + } + + /// + /// Defines the time at which the file or directory was last accessed + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetLastAccessTimeAsync( string path, DateTime lastAccessTime ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetLastAccessTime( path, lastAccessTime ) ); + } + /// + /// Defines the time at which the file or directory was last accessed + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx + public static Task SetLastAccessTimeAsync( QuickIOPathInfo info, DateTime lastAccessTime ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetLastAccessTime( info, lastAccessTime ) ); + } + /// + /// Defines the time at which the file or directory was last accessed + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx + public static Task SetLastAccessTimeAsync( <#= className #>Info info, DateTime lastAccessTime ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetLastAccessTime( info, lastAccessTime ) ); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static Task SetLastAccessTimeUtcAsync( string path, DateTime lastAccessTimeUtc ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetLastAccessTimeUtc( path, lastAccessTimeUtc ) ); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static Task SetLastAccessTimeUtcAsync( QuickIOPathInfo info, DateTime lastAccessTimeUtc ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetLastAccessTimeUtc( info, lastAccessTimeUtc ) ); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static Task SetLastAccessTimeUtcAsync( <#= className #>Info info, DateTime lastAccessTimeUtc ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetLastAccessTimeUtc( info, lastAccessTimeUtc ) ); + } + + /// + /// Defines the time at which the file or directory was last written + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetLastWriteTimeAsync( string path, DateTime lastWriteTime ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetLastWriteTime( path, lastWriteTime ) ); + } + /// + /// Defines the time at which the file or directory was last written + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx + public static Task SetLastWriteTimeAsync( QuickIOPathInfo info, DateTime lastWriteTime ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetLastWriteTime( info, lastWriteTime ) ); + } + /// + /// Defines the time at which the file or directory was last written + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx + public static Task SetLastWriteTimeAsync( <#= className #>Info info, DateTime lastWriteTime ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetLastWriteTime( info, lastWriteTime ) ); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static Task SetLastWriteTimeUtcAsync( string path, DateTime lastWriteTimeUtc ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetLastWriteTimeUtc( path, lastWriteTimeUtc ) ); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static Task SetLastWriteTimeUtcAsync( QuickIOPathInfo info, DateTime lastWriteTimeUtc ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetLastWriteTimeUtc( info, lastWriteTimeUtc ) ); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// <#= pathPassValueText #> + /// <#=dateTimePassValueText#> (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static Task SetLastWriteTimeUtcAsync( <#= className #>Info info, DateTime lastWriteTimeUtc ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( () => <#= className #>.SetLastWriteTimeUtc( info, lastWriteTimeUtc ) ); + } +} +<#+ + } +#> diff --git a/src/QuickIO/CodeTemplates/StaticRootMethods.cs b/src/QuickIO/CodeTemplates/StaticRootMethods.cs new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/src/QuickIO/CodeTemplates/StaticRootMethods.cs @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/QuickIO/CodeTemplates/StaticRootMethods.tt b/src/QuickIO/CodeTemplates/StaticRootMethods.tt new file mode 100644 index 0000000..bd072ae --- /dev/null +++ b/src/QuickIO/CodeTemplates/StaticRootMethods.tt @@ -0,0 +1,44 @@ +<#+ +void Generate(string className) +{ + #> +namespace SchwabenCode.QuickIO; + +public partial class <#= className #> +{ + /// + /// Returns the root information + /// + /// The path of a file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static QuickIOPathInfo? GetDirectoryRoot( string path ) + { + return GetDirectoryRoot( new QuickIOPathInfo ( path ) ); + } + + /// + /// Returns the root information + /// + /// A file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static QuickIOPathInfo? GetDirectoryRoot( QuickIOPathInfo info ) + { + return info.Root; + } + + /// + /// Returns the root information + /// + /// A file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static QuickIOPathInfo? GetDirectoryRoot( <#= className #>Info info ) + { + return info.Root; + } +} +<#+ +} +#> diff --git a/src/QuickIO/CodeTemplates/StaticRootMethods_Async.cs b/src/QuickIO/CodeTemplates/StaticRootMethods_Async.cs new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/src/QuickIO/CodeTemplates/StaticRootMethods_Async.cs @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/QuickIO/CodeTemplates/StaticRootMethods_Async.tt b/src/QuickIO/CodeTemplates/StaticRootMethods_Async.tt new file mode 100644 index 0000000..19a4b28 --- /dev/null +++ b/src/QuickIO/CodeTemplates/StaticRootMethods_Async.tt @@ -0,0 +1,47 @@ +<#+ +void Generate(string className) +{#> +using System; +using System.Threading.Tasks; +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class <#= className #> +{ + /// + /// Returns the root information + /// + /// The path of a file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static Task GetDirectoryRootAsync( string path ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( ( ) => <#= className #>.GetDirectoryRoot( path ) ); + } + + /// + /// Returns the root information + /// + /// A file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static Task GetDirectoryRootAsync( QuickIOPathInfo info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( ( ) => <#= className #>.GetDirectoryRoot( info ) ); + } + + /// + /// Returns the root information + /// + /// A file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static Task GetDirectoryRootAsync( <#= className #>Info info ) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult( ( ) => <#= className #>.GetDirectoryRoot( info ) ); + } +} +<#+ +} +#> diff --git a/src/QuickIO/Compatibility/NETCompatibility.cs b/src/QuickIO/Compatibility/NETCompatibility.cs new file mode 100644 index 0000000..c6eb972 --- /dev/null +++ b/src/QuickIO/Compatibility/NETCompatibility.cs @@ -0,0 +1,74 @@ +namespace SchwabenCode.QuickIO.Compatibility; + +public static class NETCompatibility +{ + /// + /// Several methods for async operations + /// + public static class AsyncExtensions + { + private static readonly TaskFactory s_asyncTaskFactory = Task.Factory; + + /// + /// Executes the action in a wrapped task to use async operation + /// + /// Result Type + /// Action to execute in wrapped task + /// Returns this value if finished + /// + public static Task ExecuteAsyncResult(Action action, T resultValue) + { + TaskCompletionSource tcs = new( ); + + _ = s_asyncTaskFactory.StartNew(() => + { + try + { + action(); + tcs.SetResult(resultValue); + } + catch (Exception ex) + { + tcs.SetException(ex); + } + }); + + return tcs.Task; + } + + /// + /// Executes the action in a wrapped task to use async operation and gets the result + /// + /// Result Type + /// Action to execute in wrapped task + /// with result value + public static Task GetAsyncResult(Func action) + { + TaskCompletionSource tcs = new( ); + + _ = s_asyncTaskFactory.StartNew(() => + { + try + { + tcs.SetResult(action()); + } + catch (Exception ex) + { + tcs.SetException(ex); + } + }); + + return tcs.Task; + } + + /// + /// Executes the action in a wrapped task to use async operation + /// + /// Action to execute in wrapped task + /// + public static Task ExecuteAsync(Action action) + { + return s_asyncTaskFactory.StartNew(action); + } + } +} diff --git a/src/QuickIO/DirectoryAlreadyExistsException.cs b/src/QuickIO/DirectoryAlreadyExistsException.cs new file mode 100644 index 0000000..3de86dd --- /dev/null +++ b/src/QuickIO/DirectoryAlreadyExistsException.cs @@ -0,0 +1,16 @@ +namespace SchwabenCode.QuickIO; + +/// +/// This error is raised if you want to create for example a folder which already exists. +/// +[Serializable] +public class DirectoryAlreadyExistsException : QuickIOBaseException +{ + /// + /// Creates an instance of + /// + /// Error message + /// Affected directory path + public DirectoryAlreadyExistsException(string message, string path) + : base(message, path) { } +} diff --git a/src/QuickIO/DirectoryNotEmptyException.cs b/src/QuickIO/DirectoryNotEmptyException.cs new file mode 100644 index 0000000..b5aa9c9 --- /dev/null +++ b/src/QuickIO/DirectoryNotEmptyException.cs @@ -0,0 +1,18 @@ +namespace SchwabenCode.QuickIO; + +/// +/// This error is raised if a folder that is not empty should be deleted. +/// +[Serializable] +public class DirectoryNotEmptyException : QuickIOBaseException +{ + /// + /// Creates an instance of + /// + /// Error message + /// Affected directory path + public DirectoryNotEmptyException(string message, string path) + : base(message, path) + { + } +} diff --git a/src/QuickIO/FileAlreadyExistsException.cs b/src/QuickIO/FileAlreadyExistsException.cs new file mode 100644 index 0000000..1f8898d --- /dev/null +++ b/src/QuickIO/FileAlreadyExistsException.cs @@ -0,0 +1,30 @@ +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +/// +/// This error is raised if a file should be created that already exists. +/// +[Serializable] +public class FileAlreadyExistsException : QuickIOBaseException +{ + /// + /// Creates an instance of + /// + /// Affected file path + public FileAlreadyExistsException(string path) + : base(Win32ErrorCodes.FormatMessage(Win32ErrorCodes.ERROR_ALREADY_EXISTS), path) + { + } + + /// + /// Creates an instance of + /// + /// Error message + /// Affected file path + public FileAlreadyExistsException(string message, string path) + : base(message, path) + { + } +} + diff --git a/src/QuickIO/FileSystemIsBusyException.cs b/src/QuickIO/FileSystemIsBusyException.cs new file mode 100644 index 0000000..29c5e4b --- /dev/null +++ b/src/QuickIO/FileSystemIsBusyException.cs @@ -0,0 +1,18 @@ +namespace SchwabenCode.QuickIO; + +/// +/// This error is raised if file system is busy and further operations are not able to execute +/// +[Serializable] +public class FileSystemIsBusyException : QuickIOBaseException +{ + /// + /// Creates an instance of + /// + /// Error message + /// Affected directory path + public FileSystemIsBusyException(string message, string path) + : base(message, path) + { + } +} diff --git a/src/QuickIO/Internal/InternalHelpers.cs b/src/QuickIO/Internal/InternalHelpers.cs new file mode 100644 index 0000000..fed255a --- /dev/null +++ b/src/QuickIO/Internal/InternalHelpers.cs @@ -0,0 +1,105 @@ +namespace SchwabenCode.QuickIO.Internal; + +internal static class InternalHelpers +{ + /// + /// Adds another to the existing collection + /// + /// collection + /// Attribute to add or remove + /// true to add, false to remove + /// + public static FileAttributes ForceFileAttributesExistance(FileAttributes source, FileAttributes attr, bool existance) + { + return existance ? AddFileAttrribute(source, attr) : RemoveFileAttribute(source, attr); + } + + /// + /// Checks whether an attribute is already in the collection; If not, it will be added. + /// Returns true on add. False if the collection already contains that attribute. + /// + /// collection + /// Attribute to add or remove + /// true to add, false to remove + /// FileAttributes after update + /// True if the collection has been updated . + public static bool TryForceFileAttributesExistance(FileAttributes source, FileAttributes attr, bool existance, out FileAttributes updatedSource) + { + return existance ? TryAddFileAttrribute(source, attr, out updatedSource) : TryRemoveFileAttrribute(source, attr, out updatedSource); + } + + /// + /// Adds a to the existing collection . + /// Returns true on add. False if the collection already contains that attribute. + /// + /// collection + /// Attribute to add + /// FileAttributes after update + /// True if attributes updated + public static bool TryAddFileAttrribute(FileAttributes source, FileAttributes attr, out FileAttributes updatedSource) + { + if (ContainsFileAttribute(source, attr)) + { + updatedSource = source; + return false; + } + + updatedSource = AddFileAttrribute(source, attr); + return true; + } + + /// + /// Adds a to the existing collection . + /// + /// collection + /// Attribute to add + /// + public static FileAttributes AddFileAttrribute(FileAttributes source, FileAttributes attr) + { + source |= attr; + return source; + } + + /// + /// Removes a to the existing collection . + /// Returns true on remove. False if the collection does not contain that attribute. + /// + /// collection + /// Attribute to remove + /// FileAttributes after update + /// True if attributes updated + public static bool TryRemoveFileAttrribute(FileAttributes source, FileAttributes attr, out FileAttributes updatedSource) + { + if (ContainsFileAttribute(source, attr)) + { + updatedSource = source; + return false; + } + + updatedSource = RemoveFileAttribute(source, attr); + return true; + } + + /// + /// Removes a to the existing collection . + /// + /// collection + /// Attribute to remove + /// + public static FileAttributes RemoveFileAttribute(FileAttributes source, FileAttributes attr) + { + source &= attr; + return source; + } + + /// + /// Checks whether the given attribute in the collection is included. + /// + /// collection + /// Attribute to check + /// True if exists, false if not + public static bool ContainsFileAttribute(FileAttributes source, FileAttributes attr) + { + return (source & attr) != 0; + } +} diff --git a/src/QuickIO/Internal/InternalQuickIO.cs b/src/QuickIO/Internal/InternalQuickIO.cs new file mode 100644 index 0000000..83144e7 --- /dev/null +++ b/src/QuickIO/Internal/InternalQuickIO.cs @@ -0,0 +1,1361 @@ +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; +using SchwabenCode.QuickIO.Compatibility; +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO.Internal; + +/// +/// Provides internal methods. All IO operations are called from here. +/// +internal static class InternalQuickIO +{ + /// + /// Creates a new file. + /// + /// The specified path already exists. + /// This error is fired if the specified path or a part of them does not exist. + public static void CreateFile(QuickIOPathInfo pathInfo, FileAccess fileAccess = FileAccess.Write, FileShare fileShare = FileShare.None, FileMode fileMode = FileMode.Create, FileAttributes fileAttributes = 0) + { + using SafeFileHandle fileHandle = Win32SafeNativeMethods.CreateFile(pathInfo.FullNameUnc, fileAccess, fileShare, IntPtr.Zero, fileMode, fileAttributes, IntPtr.Zero); + int win32Error = Marshal.GetLastWin32Error( ); + if (fileHandle.IsInvalid) + { + InternalQuickIOCommon.NativeExceptionMapping(pathInfo.FullName, win32Error); + } + } + + /// + /// Removes a file. + /// + /// Path to the file to remove + /// This error is fired if the specified file to remove does not exist. + public static void DeleteFile(string path) + { + // Remove all attributes + RemoveAllFileAttributes(path); + + bool result = Win32SafeNativeMethods.DeleteFile( path ); + int win32Error = Marshal.GetLastWin32Error( ); + if (!result) + { + InternalQuickIOCommon.NativeExceptionMapping(path, win32Error); + } + } + + /// + /// Sets all attributes to + /// + /// Path to file or directory + /// This error will be fired if the specified path or a part of them does not exist. + public static void RemoveAllFileAttributes(string path) + { + SetAttributes(path, FileAttributes.Normal); + } + + /// + /// Removes a file. + /// + /// PathInfo of the file to remove + /// This error is fired if the specified file to remove does not exist. + public static void DeleteFile(QuickIOPathInfo pathInfo) + { + DeleteFile(pathInfo.FullNameUnc); + } + + /// + /// Removes a file. + /// + /// FileInfo of the file to remove + /// This error will be fired if the specified path or a part of them does not exist. + /// This error will be fired when attempting a file to delete, which does not exist. + public static void DeleteFile(QuickIOFileInfo fileInfo) + { + DeleteFile(fileInfo.PathInfo); + } + + /// + /// Remove a file attribute + /// + /// Affected target + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static bool RemoveAttribute(QuickIOPathInfo pathInfo, FileAttributes attribute) + { + if ((pathInfo.Attributes & attribute) == attribute) + { + FileAttributes attributes = pathInfo.Attributes; + attributes &= ~attribute; + SetAttributes(pathInfo, attributes); + return true; + } + return false; + } + + /// + /// Remove a file attribute + /// + /// Affected target + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static bool RemoveAttribute(string path, FileAttributes attribute) + { + FileAttributes currentAttributes = GetAttributes( path ); + + if ((currentAttributes & attribute) == attribute) + { + FileAttributes attributes = currentAttributes; + attributes &= ~attribute; + SetAttributes(path, attributes); + return true; + } + return false; + } + + + /// + /// Adds a file attribute + /// + /// Affected target + /// Attribute to add + /// true if added. false if already exists in attributes + public static bool AddAttribute(QuickIOPathInfo pathInfo, FileAttributes attribute) + { + if ((pathInfo.Attributes & attribute) != attribute) + { + FileAttributes attributes = pathInfo.Attributes; + attributes |= attribute; + SetAttributes(pathInfo, attributes); + return true; + } + + return false; + } + + + /// + /// Creates a new directory. If is false, the parent directory must exists. + /// + /// + /// If is false, the parent directory must exist. + /// The specified path already exists. + /// This error is fired if the specified path or a part of them does not exist. + public static void CreateDirectory(QuickIOPathInfo pathInfo, bool recursive = false) + { + if (QuickIODirectory.Exists(pathInfo)) + { + return; + } + + if (pathInfo.IsRoot) + { + throw new PathNotFoundException("Root directory " + pathInfo.FullName + " does not exists and cannot be created."); + } + + if (recursive) + { + QuickIOPathInfo? parent = pathInfo.Parent ?? throw new PathNotFoundException("Root directory " + pathInfo.FullName + " does not exists and cannot be created."); + if (parent.IsRoot) + { + // Root + if (!parent.Exists) + { + throw new PathNotFoundException("Root path does not exists. You cannot create a root this way.", parent.FullName); + } + + } + else if (!parent.Exists) + { + CreateDirectory(parent, recursive); + } + } + + bool created = Win32SafeNativeMethods.CreateDirectory( pathInfo.FullNameUnc, IntPtr.Zero ); + int win32Error = Marshal.GetLastWin32Error( ); + if (!created) + { + InternalQuickIOCommon.NativeExceptionMapping(pathInfo.FullName, win32Error); + } + } + + /// + /// Deletes all files in the given directory. + /// + /// Path of directory to clear + /// If true all files in all all subfolders included + /// This error is fired if the specified path or a part of them does not exist. + /// This error will be fired when attempting a file to delete, which does not exist. + public static void DeleteFiles(string directoryPath, bool recursive = false) + { + IEnumerable allFilePaths = EnumerateFilePaths( directoryPath, QuickIOPatternConstants.All, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions.None ); + foreach (string filePath in allFilePaths) + { + DeleteFile(filePath); + } + } + + /// + /// Deletes all files in the given directory. On request all contents, too. + /// + /// PathInfo of directory to clear + /// If is true then all subfolders are also deleted. + /// This error is fired if the specified path or a part of them does not exist. + /// The directory is not empty. + /// Function loads every file and attribute. Alls read-only flags will be removed before removing. + public static void DeleteDirectory(QuickIOPathInfo pathInfo, bool recursive = false) + { + DeleteDirectory(new QuickIODirectoryInfo(pathInfo), recursive); + } + + /// + /// Deletes all files in the given directory. On request all contents, too. + /// + /// Info of directory to clear + /// If is true then all subfolders are also deleted. + /// This error is fired if the specified path or a part of them does not exist. + /// The directory is not empty. + /// Function loads every file and attribute. Alls read-only flags will be removed before removing. + public static void DeleteDirectory(QuickIODirectoryInfo directoryInfo, bool recursive = false) + { + // Contents + if (recursive) + { + // search all contents + IEnumerable subFiles = QuickIODirectory.EnumerateFilePaths( directoryInfo.FullNameUnc, QuickIOPatternConstants.All, SearchOption.TopDirectoryOnly, QuickIOPathType.UNC, QuickIOEnumerateOptions.None ); + #region delete all files + foreach (string item in subFiles) + { + DeleteFile(item); + } + #endregion + + IEnumerable subDirs = QuickIODirectory.EnumerateDirectories( directoryInfo, QuickIOPatternConstants.All, SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions.None ); + + foreach (QuickIODirectoryInfo subDir in subDirs) + { + DeleteDirectory(subDir, recursive); + } + } + + // Remove specified + bool removed = Win32SafeNativeMethods.RemoveDirectory( directoryInfo.FullNameUnc ); + int win32Error = Marshal.GetLastWin32Error( ); + if (!removed) + { + InternalQuickIOCommon.NativeExceptionMapping(directoryInfo.FullName, win32Error); + } + } + + /// + /// Gets the from the passed path. + /// + /// Path + /// . Will be null if path does not exist. + /// true if path is valid and is set + /// + /// + /// QuickIOCommon.NativeExceptionMapping + /// if invalid handle found. + /// + /// This error is fired if the specified path or a part of them does not exist. + public static bool TryGetFindDataFromPath(QuickIOPathInfo pathInfo, [NotNullWhen(true)] out Win32FindData? pathFindData) + { + Win32FindData win32FindData = new( ); + + //var path = pathInfo.FullNameUnc; + //if ( pathInfo.IsRoot ) + //{ + // path = QuickIOPath.Combine( path, QuickIOPatternConstants.All ); + //} + + using (Win32FileHandle fileHandle = FindFirstSafeFileHandle(pathInfo.FullNameUnc, win32FindData, out int win32Error)) + { + // Take care of invalid handles + if (fileHandle.IsInvalid) + { + InternalQuickIOCommon.NativeExceptionMapping(pathInfo.FullName, win32Error); + } + + // Treffer auswerten + // Ignore . and .. directories + if (!InternalRawDataHelpers.IsSystemDirectoryEntry(win32FindData)) + { + pathFindData = win32FindData; + return true; + } + } + + pathFindData = null; + return false; + } + + + /// + /// Returns the and fills from the passes path. + /// + /// Path to the file system entry + /// + /// Last error code. 0 if no error occurs + /// + /// This error is fired if the specified path or a part of them does not exist. + private static Win32FileHandle FindFirstSafeFileHandle(string path, Win32FindData win32FindData, out int win32Error) + { + Win32FileHandle result = Win32SafeNativeMethods.FindFirstFile( path, win32FindData ); + win32Error = Marshal.GetLastWin32Error(); + + return result; + } + + /// + /// Reurns true if passed path exists + /// + /// Path to check + public static bool Exists(QuickIOPathInfo pathInfo) + { + return Exists(pathInfo.FullNameUnc); + } + + /// + /// Reurns true if passed path exists + /// + /// Path to check + public static bool Exists(string path) + { + uint attributes = Win32SafeNativeMethods.GetFileAttributes( path ); + return !Equals(attributes, 0xffffffff); + } + + ///// + ///// Returns the from specified + ///// + ///// Path to the file system entry + ///// + ///// This error is fired if the specified path or a part of them does not exist. + /// + /// + /// Returns the from specified + /// + /// Path to the file system entry + /// + /// This error is fired if the specified path or a part of them does not exist. + public static Win32FindData GetFindDataFromPath(QuickIOPathInfo pathInfo) + { + Win32FindData win32FindData = new( ); + using (Win32FileHandle fileHandle = FindFirstSafeFileHandle(pathInfo.FullNameUnc, win32FindData, out int win32Error)) + { + // Take care of invalid handles + if (fileHandle.IsInvalid) + { + InternalQuickIOCommon.NativeExceptionMapping(pathInfo.FullName, win32Error); + } + + // Treffer auswerten + // Ignore . and .. directories + if (!InternalRawDataHelpers.IsSystemDirectoryEntry(win32FindData)) + { + return win32FindData; + } + } + + throw new PathNotFoundException(pathInfo.FullName); + } + + /// + /// Gets the from the passed + /// + /// Path to the file system entry + /// Estimated Type (File or Directory) + /// + /// Searched for file but found folder or vise versa. + ///No entry found for passed path + public static Win32FindData GetFindDataFromPath(QuickIOPathInfo pathInfo, QuickIOFileSystemEntryType? estimatedFileSystemEntryType) + { + return GetFindDataFromPath(pathInfo.FullNameUnc, estimatedFileSystemEntryType); + } + + /// + /// Gets the from the passed path. + /// + /// Path to the file system entry + /// Estimated Type (File or Directory) + /// + /// Searched for file but found folder or vise versa. + /// No entry found for passed path + public static Win32FindData GetFindDataFromPath(string fullUncPath, QuickIOFileSystemEntryType? estimatedFileSystemEntryType) + { + Win32FindData win32FindData = new( ); + using (Win32FileHandle fileHandle = FindFirstSafeFileHandle(fullUncPath, win32FindData, out int win32Error)) + { + // Take care of invalid handles + if (fileHandle.IsInvalid) + { + InternalQuickIOCommon.NativeExceptionMapping(fullUncPath, win32Error); + } + + // Treffer auswerten + // Ignore . and .. directories + if (!InternalRawDataHelpers.IsSystemDirectoryEntry(win32FindData)) + { + + // Check for correct type + switch (estimatedFileSystemEntryType) + { + // Unimportant + case null: + { + return win32FindData; + } + case QuickIOFileSystemEntryType.Directory: + { + // Check for directory flag + if (InternalHelpers.ContainsFileAttribute(win32FindData.dwFileAttributes, FileAttributes.Directory)) + { + return win32FindData; + } + throw new UnmatchedFileSystemEntryTypeException(QuickIOFileSystemEntryType.Directory, QuickIOFileSystemEntryType.File, fullUncPath); + } + case QuickIOFileSystemEntryType.File: + { + // Check for directory flag + if (!InternalHelpers.ContainsFileAttribute(win32FindData.dwFileAttributes, FileAttributes.Directory)) + { + return win32FindData; + } + throw new UnmatchedFileSystemEntryTypeException(QuickIOFileSystemEntryType.File, QuickIOFileSystemEntryType.Directory, fullUncPath); + } + } + return win32FindData; + + } + } + throw new PathNotFoundException(fullUncPath); + } + + /// + /// Returns the and fills from the passes path. + /// + /// Path to the file system entry + /// + /// This error is fired if the specified path or a part of them does not exist. + internal static SafeFileHandle CreateSafeFileHandle(QuickIOPathInfo pathInfo) + { + return CreateSafeFileHandle(pathInfo.FullNameUnc); + } + + /// + /// Returns the and fills from the passes path. + /// + /// Path to the file system entry + /// + /// This error is fired if the specified path or a part of them does not exist. + private static SafeFileHandle CreateSafeFileHandle(string path) + { + return Win32SafeNativeMethods.CreateFile(path, FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero); + } + + /// + /// Returns the and fills from the passes path. + /// + /// Path to the file system entry + /// + /// This error is fired if the specified path or a part of them does not exist. + internal static SafeFileHandle OpenReadWriteFileSystemEntryHandle(string path) + { + return Win32SafeNativeMethods.OpenReadWriteFileSystemEntryHandle(path, (0x40000000 | 0x80000000), FileShare.Read | FileShare.Write | FileShare.Delete, IntPtr.Zero, FileMode.Open, (0x02000000), IntPtr.Zero); + } + + /// + /// Determined metadata of directory + /// + /// Path of the directory + /// The enumeration options for exception handling + /// started with the given directory + /// This error is fired if the specified path or a part of them does not exist. + internal static QuickIODirectoryMetadata? EnumerateDirectoryMetadata(QuickIOPathInfo pathInfo, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return EnumerateDirectoryMetadata(pathInfo.FullNameUnc, pathInfo.FindData, enumerateOptions); + } + + /// + /// Determined metadata of directory + /// + /// Path of the directory + /// + /// The enumeration options for exception handling + /// started with the given directory + /// This error is fired if the specified path or a part of them does not exist. + internal static QuickIODirectoryMetadata? EnumerateDirectoryMetadata( + string uncDirectoryPath, Win32FindData findData, QuickIOEnumerateOptions enumerateOptions) + { + // Results + List subFiles = []; + List subDirs = []; + + // Match for start of search + string currentPath = QuickIOPath.Combine( uncDirectoryPath, QuickIOPatternConstants.All ); + + // Find First file + Win32FindData win32FindData = new( ); + using (Win32FileHandle fileHandle = FindFirstSafeFileHandle(currentPath, win32FindData, out int win32Error)) + { + // Take care of invalid handles + if (fileHandle.IsInvalid) + { + if (win32Error != Win32ErrorCodes.ERROR_NO_MORE_FILES) + { + InternalQuickIOCommon.NativeExceptionMapping(uncDirectoryPath, win32Error); + } + + if (EnumerationHandleInvalidFileHandle(uncDirectoryPath, enumerateOptions, win32Error)) + { + return null; + } + } + + // Treffer auswerten + do + { + // Ignore . and .. directories + if (InternalRawDataHelpers.IsSystemDirectoryEntry(win32FindData)) + { + continue; + } + + // Create hit for current search result + string uncResultPath = QuickIOPath.Combine( uncDirectoryPath, win32FindData.cFileName ); + + // if it's a file, add to the collection + if (!InternalHelpers.ContainsFileAttribute(win32FindData.dwFileAttributes, FileAttributes.Directory)) + { + QuickIOFileMetadata fileMetaData = new( uncResultPath, win32FindData ); + subFiles.Add(fileMetaData); + } + else + { + QuickIODirectoryMetadata? dir = EnumerateDirectoryMetadata( uncResultPath, win32FindData, enumerateOptions ); + if (dir is not null) + { + subDirs.Add(dir); + } + } + // Create new FindData object for next result + + win32FindData = new Win32FindData(); + } // Search for next entry + while (Win32SafeNativeMethods.FindNextFile(fileHandle, win32FindData)); + } + + return new QuickIODirectoryMetadata(uncDirectoryPath, findData, subDirs, subFiles); + } + + + /// + /// Determined all subfolders of a directory + /// + /// Path of the directory + /// Search pattern. Uses Win32 native filtering. + /// + /// The enumeration options for exception handling + /// collection of subfolders + /// This error is fired if the specified path or a part of them does not exist. + internal static IEnumerable EnumerateDirectories(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + // Match for start of search + string currentPath = QuickIOPath.Combine( pathInfo.FullNameUnc, pattern ); + + // Find First file + Win32FindData win32FindData = new( ); + using Win32FileHandle fileHandle = FindFirstSafeFileHandle(currentPath, win32FindData, out int win32Error); + + // Take care of invalid handles + if (fileHandle.IsInvalid) + { + if (win32Error != Win32ErrorCodes.ERROR_NO_MORE_FILES) + { + InternalQuickIOCommon.NativeExceptionMapping(pathInfo.FullName, win32Error); + } + + if (EnumerationHandleInvalidFileHandle(pathInfo.FullName, enumerateOptions, win32Error)) + { + yield break; + } + } + + do + { + // Ignore . and .. directories + if (InternalRawDataHelpers.IsSystemDirectoryEntry(win32FindData)) + { + continue; + } + + // Create hit for current search result + string resultPath = QuickIOPath.Combine( pathInfo.FullName, win32FindData.cFileName ); + + // Check for Directory + if (InternalHelpers.ContainsFileAttribute(win32FindData.dwFileAttributes, FileAttributes.Directory)) + { + yield return new QuickIODirectoryInfo(resultPath, win32FindData); + + // SubFolders?! + if (searchOption == SearchOption.AllDirectories) + { + foreach (QuickIODirectoryInfo match in EnumerateDirectories(new QuickIOPathInfo(resultPath, win32FindData.cFileName), pattern, searchOption, enumerateOptions)) + { + yield return match; + } + } + } + // Create new FindData object for next result + win32FindData = new Win32FindData(); + } // Search for next entry + while (Win32SafeNativeMethods.FindNextFile(fileHandle, win32FindData)); + } + + /// + /// Determined all sub system entries of a directory + /// + /// Path of the directory + /// Search pattern. Uses Win32 native filtering. + /// + /// The enumeration options for exception handling + /// Collection of + /// This error is fired if the specified path or a part of them does not exist. + internal static IEnumerable> EnumerateFileSystemEntries(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return EnumerateFileSystemEntries(pathInfo.FullNameUnc, pattern, searchOption, enumerateOptions); + } + + /// + /// Determined all sub system entries of a directory + /// + /// Path of the directory + /// Search pattern. Uses Win32 native filtering. + /// + /// The enumeration options for exception handling + /// Collection of + /// This error is fired if the specified path or a part of them does not exist. + private static IEnumerable> EnumerateFileSystemEntries(string uncDirectoryPath, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + // Match for start of search + string currentPath = QuickIOPath.Combine( uncDirectoryPath, pattern ); + + // Find First file + Win32FindData win32FindData = new( ); + using Win32FileHandle fileHandle = FindFirstSafeFileHandle(currentPath, win32FindData, out int win32Error); + // Take care of invalid handles + if (fileHandle.IsInvalid) + { + if (win32Error != Win32ErrorCodes.ERROR_NO_MORE_FILES) + { + InternalQuickIOCommon.NativeExceptionMapping(uncDirectoryPath, win32Error); + } + + if (EnumerationHandleInvalidFileHandle(uncDirectoryPath, enumerateOptions, win32Error)) + { + yield return new KeyValuePair(); + } + } + + // Treffer auswerten + do + { + // Ignore . and .. directories + if (InternalRawDataHelpers.IsSystemDirectoryEntry(win32FindData)) + { + continue; + } + + // Create hit for current search result + string resultPath = QuickIOPath.Combine( uncDirectoryPath, win32FindData.cFileName ); + + // Check for Directory + if (InternalHelpers.ContainsFileAttribute(win32FindData.dwFileAttributes, FileAttributes.Directory)) + { + yield return new KeyValuePair(new QuickIOPathInfo(resultPath) { FindData = win32FindData }, QuickIOFileSystemEntryType.Directory); + + // SubFolders?! + if (searchOption == SearchOption.AllDirectories) + { + foreach (KeyValuePair match in EnumerateFileSystemEntries(new QuickIOPathInfo(resultPath, win32FindData.cFileName), pattern, searchOption, enumerateOptions)) + { + yield return match; + } + } + } + else + { + yield return new KeyValuePair(new QuickIOPathInfo(resultPath) { FindData = win32FindData }, QuickIOFileSystemEntryType.File); + + } + // Create new FindData object for next result + win32FindData = new Win32FindData(); + } // Search for next entry + while (Win32SafeNativeMethods.FindNextFile(fileHandle, win32FindData)); + } + + /// + /// Determined all sub file system entries of a directory + /// + /// Path of the directory + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// The enumeration options for exception handling + /// Collection of + /// This error is fired if the specified path or a part of them does not exist. + internal static IEnumerable> EnumerateFileSystemEntryPaths(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular) + { + return EnumerateFileSystemEntryPaths(pathInfo.FullNameUnc, pattern, searchOption, enumerateOptions, pathFormatReturn); + } + + /// + /// Determined all sub file system entries of a directory + /// + /// Path of the directory + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// The enumeration options for exception handling + /// Collection of + /// This error is fired if the specified path or a part of them does not exist. + private static IEnumerable> EnumerateFileSystemEntryPaths(string uncDirectoryPath, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular) + { + // Match for start of search + string currentPath = QuickIOPath.Combine( uncDirectoryPath, pattern ); + + // Find First file + Win32FindData win32FindData = new( ); + using Win32FileHandle fileHandle = FindFirstSafeFileHandle(currentPath, win32FindData, out int win32Error); + // Take care of invalid handles + if (fileHandle.IsInvalid) + { + if (win32Error != Win32ErrorCodes.ERROR_NO_MORE_FILES) + { + InternalQuickIOCommon.NativeExceptionMapping(uncDirectoryPath, win32Error); + } + + if (EnumerationHandleInvalidFileHandle(uncDirectoryPath, enumerateOptions, win32Error)) + { + yield return new KeyValuePair(); + } + } + + // Treffer auswerten + do + { + // Ignore . and .. directories + if (InternalRawDataHelpers.IsSystemDirectoryEntry(win32FindData)) + { + continue; + } + + // Create hit for current search result + string resultPath = QuickIOPath.Combine( uncDirectoryPath, win32FindData.cFileName ); + + // Check for Directory + if (InternalHelpers.ContainsFileAttribute(win32FindData.dwFileAttributes, FileAttributes.Directory)) + { + yield return new KeyValuePair(FormatPathByType(pathFormatReturn, resultPath), QuickIOFileSystemEntryType.Directory); + + // SubFolders?! + if (searchOption == SearchOption.AllDirectories) + { + foreach (KeyValuePair match in EnumerateFileSystemEntryPaths(resultPath, pattern, searchOption, enumerateOptions, pathFormatReturn)) + { + yield return match; + } + } + } + else + { + yield return new KeyValuePair(FormatPathByType(pathFormatReturn, resultPath), QuickIOFileSystemEntryType.File); + + } + // Create new FindData object for next result + win32FindData = new Win32FindData(); + } // Search for next entry + while (Win32SafeNativeMethods.FindNextFile(fileHandle, win32FindData)); + } + + + /// + /// Determined all sub directory paths of a directory + /// + /// Path of the directory + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// The enumeration options for exception handling + /// Collection of directory paths + /// This error is fired if the specified path or a part of them does not exist. + internal static IEnumerable EnumerateDirectoryPaths(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular) + { + return FindPaths(path, pattern, searchOption, QuickIOFileSystemEntryType.Directory, enumerateOptions, pathFormatReturn); + } + + /// + /// Determined all files of a directory + /// + /// Path of the directory + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// Collection of files + /// This error is fired if the specified path or a part of them does not exist. + internal static IEnumerable EnumerateFiles(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return EnumerateFiles(pathInfo.FullNameUnc, pattern, searchOption, enumerateOptions); + } + + /// + /// Returns the handle by given path and finddata + /// + /// Specified path + /// FindData to fill + /// Win32Error Code. 0 on success + /// of specified path + private static Win32FileHandle FindFirstFileManaged(string uncPath, Win32FindData win32FindData, out int win32Error) + { + Win32FileHandle handle = Win32SafeNativeMethods.FindFirstFile( uncPath, win32FindData ); + win32Error = Marshal.GetLastWin32Error(); + return handle; + } + + /// + /// Determined all files of a directory + /// + /// Path of the directory + /// Search pattern. Uses Win32 native filtering. + /// + /// The enumeration options for exception handling + /// Collection of files + /// This error is fired if the specified path or a part of them does not exist. + internal static IEnumerable EnumerateFiles(string uncDirectoryPath, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + // Match for start of search + string currentPath = QuickIOPath.Combine( uncDirectoryPath, pattern ); + + // Find First file + Win32FindData win32FindData = new( ); + using Win32FileHandle fileHandle = FindFirstFileManaged(currentPath, win32FindData, out int win32Error); + // Take care of invalid handles + if (fileHandle.IsInvalid && EnumerationHandleInvalidFileHandle(uncDirectoryPath, enumerateOptions, win32Error)) + { + yield break; + } + + // Treffer auswerten + do + { + // Ignore . and .. directories + if (InternalRawDataHelpers.IsSystemDirectoryEntry(win32FindData)) + { + continue; + } + + // Create hit for current search result + string resultPath = QuickIOPath.Combine( uncDirectoryPath, win32FindData.cFileName ); + + // Check for Directory + if (!InternalHelpers.ContainsFileAttribute(win32FindData.dwFileAttributes, FileAttributes.Directory)) + { + yield return new QuickIOFileInfo(resultPath, win32FindData); + } + else + { + // SubFolders?! + if (searchOption == SearchOption.AllDirectories) + { + foreach (QuickIOFileInfo match in EnumerateFiles(resultPath, pattern, searchOption, enumerateOptions)) + { + yield return match; + } + } + } + // Create new FindData object for next result + win32FindData = new Win32FindData(); + } // Search for next entry + while (Win32SafeNativeMethods.FindNextFile(fileHandle, win32FindData)); + } + + /// + /// Determined all files paths of a directory + /// + /// Path of the directory + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// The enumeration options for exception handling + /// Collection of file paths + /// This error is fired if the specified path or a part of them does not exist. + internal static IEnumerable EnumerateFilePaths(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular) + { + return FindPaths(path, pattern, searchOption, QuickIOFileSystemEntryType.File, enumerateOptions, pathFormatReturn); + } + + /// + /// Loads a file from specified path + /// + /// Full path + /// + /// Path exists but it's not a file; it's a directory. + /// This error is fired if the specified path or a part of them does not exist. + public static QuickIOFileInfo LoadFileFromPathInfo(QuickIOPathInfo pathInfo) + { + // Find First file + if (TryGetFindDataFromPath(pathInfo, out Win32FindData? findData)) + { + // Entry found, check for file + if (InternalQuickIOCommon.DetermineFileSystemEntry(findData) == QuickIOFileSystemEntryType.File) + { + return new QuickIOFileInfo(pathInfo, findData); + } + throw new UnmatchedFileSystemEntryTypeException(QuickIOFileSystemEntryType.File, QuickIOFileSystemEntryType.Directory, pathInfo.FullName); + } + + // Nothing found + throw new PathNotFoundException(pathInfo.FullName); + } + + /// + /// Loads a directory from specified path + /// + /// Full path + /// + /// Path exists but it's not a directory; it's a file. + /// This error is fired if the specified path or a part of them does not exist. + public static QuickIODirectoryInfo LoadDirectoryFromPathInfo(QuickIOPathInfo pathInfo) + { + // Find First file + if (TryGetFindDataFromPath(pathInfo, out Win32FindData? findData)) + { + // Entry found, check for file + if (InternalQuickIOCommon.DetermineFileSystemEntry(findData) == QuickIOFileSystemEntryType.Directory) + { + return new QuickIODirectoryInfo(pathInfo, findData); + } + throw new UnmatchedFileSystemEntryTypeException(QuickIOFileSystemEntryType.File, QuickIOFileSystemEntryType.Directory, pathInfo.FullName); + } + + // Nothing found + throw new PathNotFoundException(pathInfo.FullName); + } + + + /// + /// Search Exection + /// + /// Start directory path + /// Search pattern. Uses Win32 native filtering. + /// + /// The enumeration options for exception handling + /// Specifies the type of path to return. + /// + /// Collection of path + /// This error is fired if the specified path or a part of them does not exist. + private static List FindPaths(string uncDirectoryPath, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOFileSystemEntryType? filterType = null, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular) + { + // Result Container + List results = []; + + // Match for start of search + string currentPath = QuickIOPath.Combine( uncDirectoryPath, pattern ); + + // Find First file + Win32FindData win32FindData = new( ); + using (Win32FileHandle fileHandle = FindFirstSafeFileHandle(currentPath, win32FindData, out int win32Error)) + { + // Take care of invalid handles + if (fileHandle.IsInvalid && EnumerationHandleInvalidFileHandle(uncDirectoryPath, enumerateOptions, win32Error)) + { + return []; + } + + // Treffer auswerten + do + { + // Ignore . and .. directories + if (InternalRawDataHelpers.IsSystemDirectoryEntry(win32FindData)) + { + continue; + } + + // Create hit for current search result + string resultPath = QuickIOPath.Combine( uncDirectoryPath, win32FindData.cFileName ); + + // if it's a file, add to the collection + if (!InternalHelpers.ContainsFileAttribute(win32FindData.dwFileAttributes, FileAttributes.Directory)) + { + if (filterType != null && ((QuickIOFileSystemEntryType)filterType == QuickIOFileSystemEntryType.File)) + { + // It's a file + results.Add(FormatPathByType(pathFormatReturn, resultPath)); + } + } + else + { + // It's a directory + // Check for search searchFocus directories + if (filterType != null && ((QuickIOFileSystemEntryType)filterType == QuickIOFileSystemEntryType.Directory)) + { + results.Add(FormatPathByType(pathFormatReturn, resultPath)); + } + + // SubFolders?! + if (searchOption == SearchOption.AllDirectories) + { + List r = new( FindPaths( resultPath, pattern, searchOption, filterType, enumerateOptions ) ); + if (r.Count > 0) + { + results.AddRange(r); + } + + } + } + + // Create new FindData object for next result + win32FindData = new Win32FindData(); + } // Search for next entry + while (Win32SafeNativeMethods.FindNextFile(fileHandle, win32FindData)); + } + + // Return result; + return results; + } + + /// + /// Handles the options to the fired exception + /// + private static bool EnumerationHandleInvalidFileHandle(string path, QuickIOEnumerateOptions enumerateOptions, int win32Error) + { + try + { + InternalQuickIOCommon.NativeExceptionMapping(path, win32Error); + } + catch (Exception) + { + if ((enumerateOptions & QuickIOEnumerateOptions.SuppressAllExceptions) == QuickIOEnumerateOptions.SuppressAllExceptions) + { + return true; + } + + throw; + } + return false; + } + + /// + /// Formats a path + /// + /// Target format type + /// Path to format + /// Formatted path + private static string FormatPathByType(QuickIOPathType pathFormatReturn, string uncPath) + { + return pathFormatReturn == QuickIOPathType.Regular ? QuickIOPath.ToRegularPath(uncPath) : uncPath; + } + + /// + /// Gets the of the file on the entry. + /// + /// The path to the entry. + /// The of the file on the entry. + /// This error is fired if the specified path or a part of them does not exist. + internal static FileAttributes GetAttributes(QuickIOPathInfo pathInfo) + { + return pathInfo.Attributes; + } + + /// + /// Gets the of the file on the entry. + /// + /// The path to the entry. + /// The of the file on the entry. + /// This error is fired if the specified path or a part of them does not exist. + internal static FileAttributes GetAttributes(string uncPath) + { + uint attrs = SafeGetAttributes( uncPath, out int win32Error ); + InternalQuickIOCommon.NativeExceptionMapping(uncPath, win32Error); + + return (FileAttributes)attrs; + } + + /// + /// Gets the of the file on the entry. + /// + /// The path to the entry. + /// Win32 Error Code + /// The of the file on the entry. + /// This error is fired if the specified path or a part of them does not exist. + internal static uint SafeGetAttributes(string uncPath, out int win32Error) + { + uint attributes = Win32SafeNativeMethods.GetFileAttributes( uncPath ); + win32Error = (attributes) == 0xffffffff ? Marshal.GetLastWin32Error() : 0; + return attributes; + } + + /// + /// Sets the specified of the entry on the specified path. + /// + /// The path to the entry. + /// A bitwise combination of the enumeration values. + /// Unmatched Exception + /// This error is fired if the specified path or a part of them does not exist. + public static void SetAttributes(QuickIOPathInfo pathInfo, FileAttributes attributes) + { + SetAttributes(pathInfo.FullNameUnc, attributes); + } + + /// + /// Sets the specified of the entry on the specified path. + /// + /// The path to the entry. + /// A bitwise combination of the enumeration values. + /// Unmatched Exception + /// This error is fired if the specified path or a part of them does not exist. + public static void SetAttributes(string path, FileAttributes attributes) + { + if (!Win32SafeNativeMethods.SetFileAttributes(path, (uint)attributes)) + { + int win32Error = Marshal.GetLastWin32Error( ); + InternalQuickIOCommon.NativeExceptionMapping(path, win32Error); + } + } + + + /// + /// Sets the specified of the entry on the specified path. + /// + /// The path to the entry. + /// A bitwise combination of the enumeration values. + /// Unmatched Exception + /// This error is fired if the specified path or a part of them does not exist. + public static Task SetAttributesAsync(QuickIOPathInfo pathInfo, FileAttributes attributes) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => SetAttributes(pathInfo, attributes)); + } + + /// + /// Copies a file and overwrite existing files if desired. + /// + /// Full source path + /// Full target path + /// Last error occured + /// true to overwrite existing files + /// True if copy succeeded, false if not. Check last Win32 Error to get further information. + /// This error is fired if the specified path or a part of them does not exist. + public static bool CopyFile(string sourceFilePath, string targetFilePath, out int win32Error, bool overwrite = false) + { + bool failOnExists = !overwrite; + + // Kopieren + bool result = Win32SafeNativeMethods.CopyFile( sourceFilePath, targetFilePath, failOnExists ); + win32Error = !result ? Marshal.GetLastWin32Error() : 0; + return result; + } + + /// + /// Determines the statistics of the given directory. This includes the number of files, folders and the total size in bytes. + /// + /// PathInfo of the directory to generate the statistics. + /// Options + /// Provides the statistics of the directory + /// This error is fired if the specified path or a part of them does not exist. + public static QuickIOFolderStatisticResult? GetDirectoryStatistics( + QuickIOPathInfo pathInfo, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return GetDirectoryStatistics(pathInfo.FullNameUnc, enumerateOptions); + } + + /// + /// Determines metadata of network shares + /// + /// Share to check + /// + public static QuickIODiskInformation GetDiskInformation(string rootPath) + { + /* PInvoke request */ + if (!Win32SafeNativeMethods.GetDiskFreeSpaceEx(rootPath, out ulong freeBytes, out ulong totalBytes, out ulong totalFreeBytes)) + { + int win32Error = Marshal.GetLastWin32Error( ); + InternalQuickIOCommon.NativeExceptionMapping(rootPath, win32Error); + } + + return new QuickIODiskInformation(freeBytes, totalBytes, totalFreeBytes); + } + + /// + /// Determines the statistics of the given directory. This includes the number of files, folders and the total size in bytes. + /// + /// Path to the directory to generate the statistics. + /// Options + /// Provides the statistics of the directory + /// This error is fired if the specified path or a part of them does not exist. + public static QuickIOFolderStatisticResult? GetDirectoryStatistics( + string path, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + ulong fileCount = 0; + ulong folderCount = 0; + ulong totalSize = 0; + + // Match for start of search + string currentPath = QuickIOPath.Combine( path, QuickIOPatternConstants.All ); + + // Find First file + Win32FindData win32FindData = new( ); + using (Win32FileHandle fileHandle = FindFirstSafeFileHandle(currentPath, win32FindData, out int win32Error)) + { + // Take care of invalid handles + if (fileHandle.IsInvalid) + { + if (EnumerationHandleInvalidFileHandle(currentPath, enumerateOptions, win32Error)) + { + return null; + } + } + + // Treffer auswerten + do + { + // Ignore . and .. directories + if (InternalRawDataHelpers.IsSystemDirectoryEntry(win32FindData)) + { + continue; + } + + // Create hit for current search result + string resultPath = QuickIOPath.Combine( path, win32FindData.cFileName ); + + // if it's a file, add to the collection + if (!InternalHelpers.ContainsFileAttribute(win32FindData.dwFileAttributes, FileAttributes.Directory)) + { + fileCount++; + totalSize += win32FindData.CalculateBytes(); _ = win32FindData.CalculateBytes(); + } + else + { + folderCount++; + QuickIOFolderStatisticResult? result = GetDirectoryStatistics( resultPath, enumerateOptions ); + if (result is not null) + { + folderCount += result.FolderCount; + fileCount += result.FileCount; + totalSize += result.TotalBytes; + } + } + + // Create new FindData object for next result + win32FindData = new Win32FindData(); + } // Search for next entry + while (Win32SafeNativeMethods.FindNextFile(fileHandle, win32FindData)); + } + + + // Return result; + return new QuickIOFolderStatisticResult(0, fileCount, 0); + } + + /// + /// Moves a file + /// + /// Full source path + /// Full target path + public static void MoveFile(string sourceFileName, string destFileName) + { + if (!Win32SafeNativeMethods.MoveFile(sourceFileName, destFileName)) + { + int win32Error = Marshal.GetLastWin32Error( ); + InternalQuickIOCommon.NativeExceptionMapping(sourceFileName, win32Error); + } + } + + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static void SetAllFileTimes(QuickIOPathInfo pathInfo, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + long longCreateTime = creationTimeUtc.ToFileTime( ); + long longAccessTime = lastAccessTimeUtc.ToFileTime( ); + long longWriteTime = lastWriteTimeUtc.ToFileTime( ); + + using SafeFileHandle fileHandle = OpenReadWriteFileSystemEntryHandle(pathInfo.FullNameUnc); + if (Win32SafeNativeMethods.SetAllFileTimes(fileHandle, ref longCreateTime, ref longAccessTime, ref longWriteTime) == 0) + { + int win32Error = Marshal.GetLastWin32Error( ); + InternalQuickIOCommon.NativeExceptionMapping(pathInfo.FullName, win32Error); + } + } + + /// + /// Sets the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + public static void SetCreationTimeUtc(QuickIOPathInfo pathInfo, DateTime utcTime) + { + long longTime = utcTime.ToFileTime( ); + using SafeFileHandle fileHandle = OpenReadWriteFileSystemEntryHandle(pathInfo.FullNameUnc); + + if (!Win32SafeNativeMethods.SetCreationFileTime(fileHandle, ref longTime, IntPtr.Zero, IntPtr.Zero)) + { + int win32Error = Marshal.GetLastWin32Error( ); + InternalQuickIOCommon.NativeExceptionMapping(pathInfo.FullName, win32Error); + } + } + + /// + /// Sets the time at which the file or directory was last written to (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + public static void SetLastWriteTimeUtc(QuickIOPathInfo pathInfo, DateTime utcTime) + { + long longTime = utcTime.ToFileTime( ); + using SafeFileHandle fileHandle = OpenReadWriteFileSystemEntryHandle(pathInfo.FullNameUnc); + if (!Win32SafeNativeMethods.SetLastWriteFileTime(fileHandle, IntPtr.Zero, IntPtr.Zero, ref longTime)) + { + int win32Error = Marshal.GetLastWin32Error( ); + InternalQuickIOCommon.NativeExceptionMapping(pathInfo.FullName, win32Error); + } + } + + /// + /// Sets the time at which the file or directory was last accessed to (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + public static void SetLastAccessTimeUtc(QuickIOPathInfo pathInfo, DateTime utcTime) + { + long longTime = utcTime.ToFileTime( ); + using SafeFileHandle fileHandle = OpenReadWriteFileSystemEntryHandle(pathInfo.FullNameUnc); + if (!Win32SafeNativeMethods.SetLastAccessFileTime(fileHandle, IntPtr.Zero, ref longTime, IntPtr.Zero)) + { + int win32Error = Marshal.GetLastWin32Error( ); + InternalQuickIOCommon.NativeExceptionMapping(pathInfo.FullName, win32Error); + } + } + + /// + /// Gets Share Result + /// + /// Machine + /// API level + /// Buffer + /// Entries total read + /// Entries total + /// Handle + /// Error Code + /// http://msdn.microsoft.com/en-us/library/windows/desktop/bb525387(v=vs.85).aspx + public static int GetShareEnumResult(string machineName, QuickIOShareApiReadLevel level, ref IntPtr buffer, ref int entriesRead, ref int totalEntries, ref int resumeHandle) + { + return Win32SafeNativeMethods.NetShareEnum(machineName, + (int)level, out buffer, -1, out entriesRead, out totalEntries, ref resumeHandle); + } +} diff --git a/src/QuickIO/Internal/InternalQuickIOCommon.cs b/src/QuickIO/Internal/InternalQuickIOCommon.cs new file mode 100644 index 0000000..e8d0e58 --- /dev/null +++ b/src/QuickIO/Internal/InternalQuickIOCommon.cs @@ -0,0 +1,97 @@ +using System.ComponentModel; +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO.Internal; + +/// +/// Provides several methods for internal purposes. +/// +internal static class InternalQuickIOCommon +{ + /// + /// Common Constants + /// + public static class Constants + { + /// + /// Represents return value of invalid request of get the file attributes of a system entry. + /// Is equal to UInt32.MaxValue + /// See http://msdn.microsoft.com/en-us/library/windows/desktop/aa364944(v=vs.85).aspx + /// + public const uint INVALID_FILE_ATTRIBUTES = 0xffffffff; + } + + /// + /// Determines the type based on the attributes of the path + /// + /// + /// + internal static QuickIOFileSystemEntryType DetermineFileSystemEntry(QuickIOPathInfo pathInfo) + { + Win32FindData findData = InternalQuickIO.GetFindDataFromPath( pathInfo ); + + return !InternalHelpers.ContainsFileAttribute(findData.dwFileAttributes, FileAttributes.Directory) ? QuickIOFileSystemEntryType.File : QuickIOFileSystemEntryType.Directory; + } + + /// + /// Determines the type based on the attributes of the handle + /// + /// + /// + internal static QuickIOFileSystemEntryType DetermineFileSystemEntry(Win32FindData findData) + { + return !InternalHelpers.ContainsFileAttribute(findData.dwFileAttributes, FileAttributes.Directory) ? QuickIOFileSystemEntryType.File : QuickIOFileSystemEntryType.Directory; + } + + + /// + /// Exception Mapping + /// + /// + /// errorCode + public static void NativeExceptionMapping(string path, int errorCode) + { + if (errorCode == Win32ErrorCodes.ERROR_SUCCESS) + { + return; + } + + string affectedPath = QuickIOPath.ToRegularPath( path ); + + // http://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx + + switch (errorCode) + { + case Win32ErrorCodes.ERROR_PATH_NOT_FOUND: + case Win32ErrorCodes.ERROR_FILE_NOT_FOUND: + throw new PathNotFoundException(Win32ErrorCodes.FormatMessage(errorCode), affectedPath); + + case Win32ErrorCodes.ERROR_ALREADY_EXISTS: + throw new PathAlreadyExistsException(Win32ErrorCodes.FormatMessage(errorCode), affectedPath); + + case Win32ErrorCodes.ERROR_INVALID_NAME: + case Win32ErrorCodes.ERROR_DIRECTORY: + throw new InvalidPathException(Win32ErrorCodes.FormatMessage(errorCode), affectedPath); + + case Win32ErrorCodes.ERROR_REM_NOT_LIST: + case Win32ErrorCodes.ERROR_NETWORK_BUSY: + case Win32ErrorCodes.ERROR_BUSY: + case Win32ErrorCodes.ERROR_PATH_BUSY: + throw new FileSystemIsBusyException(Win32ErrorCodes.FormatMessage(errorCode), affectedPath); + + case Win32ErrorCodes.ERROR_DIR_NOT_EMPTY: + throw new DirectoryNotEmptyException(Win32ErrorCodes.FormatMessage(errorCode), affectedPath); + + case Win32ErrorCodes.ERROR_ACCESS_DENIED: + case Win32ErrorCodes.ERROR_NETWORK_ACCESS_DENIED: + throw new UnauthorizedAccessException("Access to '" + affectedPath + "' denied.", new Win32Exception(errorCode)); + + case Win32ErrorCodes.ERROR_CURRENT_DIRECTORY: + case Win32ErrorCodes.ERROR_CANNOT_MAKE: + throw new Exception(Win32ErrorCodes.FormatMessage(errorCode) + affectedPath + "'.", new Win32Exception(errorCode)); + + default: + throw new Exception("Error on '" + affectedPath + "': See InnerException for details.", new Win32Exception(errorCode)); + } + } +} diff --git a/src/QuickIO/Internal/InternalRawDataHelpers.cs b/src/QuickIO/Internal/InternalRawDataHelpers.cs new file mode 100644 index 0000000..13fa8c0 --- /dev/null +++ b/src/QuickIO/Internal/InternalRawDataHelpers.cs @@ -0,0 +1,57 @@ +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO.Internal; + +/// +/// Various internal methods for the treatment of raw data +/// +internal static class InternalRawDataHelpers +{ + /// + /// Converts the PInvoke information into + /// + /// of + /// of + /// + internal static DateTime ConvertDateTime(uint high, uint low) + { + return DateTime.FromFileTimeUtc(CombineHighLowInts(high, low)); + } + + /// + /// Merges the PInvoke information + /// + /// of + /// of + internal static long CombineHighLowInts(uint high, uint low) + { + return (((long)high) << 0x20) | low; + } + + /// + /// Checks whether a directory supplied by PINvoke is relevant + /// + /// + /// true if is relevant; otherwise false + public static bool IsSystemDirectoryEntry(Win32FindData win32FindData) + { + if (win32FindData.cFileName.Length >= 3) + { + return false; + } + + return (win32FindData.cFileName == "." || win32FindData.cFileName == ".."); + } + + /// + /// Converts DateTime to Win32 FileTime format + /// + public static Win32FileTime DateTimeToFiletime(DateTime time) + { + Win32FileTime ft; + long fileTime = time.ToFileTimeUtc( ); + ft.DateTimeLow = (uint)(fileTime & 0xFFFFFFFF); + ft.DateTimeHigh = (uint)(fileTime >> 32); + return ft; + } +} diff --git a/src/QuickIO/Internal/Invariant.cs b/src/QuickIO/Internal/Invariant.cs new file mode 100644 index 0000000..36f7043 --- /dev/null +++ b/src/QuickIO/Internal/Invariant.cs @@ -0,0 +1,45 @@ +namespace SchwabenCode.QuickIO.Internal; + +/// +/// Several check methods to verify method parameters +/// +internal static class Invariant +{ + /// + /// Returns the given name + /// + /// Type + /// Property Name + /// Property Name + public static string GetName(T item) where T : class + { + return typeof(T).GetProperties()[0].Name; + } + + /// + /// Checks if specified string element is null or emoty + /// + /// Element to check + /// if is null or empty + public static void NotEmpty(string item) + { + if (string.IsNullOrEmpty(item)) + { + throw new ArgumentNullException(typeof(string).GetProperties()[0].Name); + } + } + + /// + /// has to be greater than + /// + /// Count to check + /// Reference value + public static void Greater(int count, int min) + { + if (count < min) + { + throw new ArgumentOutOfRangeException(nameof(count), + "Value has to be greather than '" + min + "' but is '" + count + "'"); + } + } +} diff --git a/src/QuickIO/InternalHelpers.cs b/src/QuickIO/InternalHelpers.cs new file mode 100644 index 0000000..0585f20 --- /dev/null +++ b/src/QuickIO/InternalHelpers.cs @@ -0,0 +1,105 @@ +namespace SchwabenCode.QuickIO; + +internal static class InternalHelpers +{ + /// + /// Adds another to the existing collection + /// + /// collection + /// Attribute to add or remove + /// true to add, false to remove + /// + public static FileAttributes ForceFileAttributesExistance(FileAttributes source, FileAttributes attr, bool existance) + { + return existance ? AddFileAttrribute(source, attr) : RemoveFileAttribute(source, attr); + } + + /// + /// Checks whether an attribute is already in the collection; If not, it will be added. + /// Returns true on add. False if the collection already contains that attribute. + /// + /// collection + /// Attribute to add or remove + /// true to add, false to remove + /// FileAttributes after update + /// True if the collection has been updated . + public static bool TryForceFileAttributesExistance(FileAttributes source, FileAttributes attr, bool existance, out FileAttributes updatedSource) + { + return existance ? TryAddFileAttrribute(source, attr, out updatedSource) : TryRemoveFileAttrribute(source, attr, out updatedSource); + } + + /// + /// Adds a to the existing collection . + /// Returns true on add. False if the collection already contains that attribute. + /// + /// collection + /// Attribute to add + /// FileAttributes after update + /// True if attributes updated + public static bool TryAddFileAttrribute(FileAttributes source, FileAttributes attr, out FileAttributes updatedSource) + { + if (ContainsFileAttribute(source, attr)) + { + updatedSource = source; + return false; + } + + updatedSource = AddFileAttrribute(source, attr); + return true; + } + + /// + /// Adds a to the existing collection . + /// + /// collection + /// Attribute to add + /// + public static FileAttributes AddFileAttrribute(FileAttributes source, FileAttributes attr) + { + source |= attr; + return source; + } + + /// + /// Removes a to the existing collection . + /// Returns true on remove. False if the collection does not contain that attribute. + /// + /// collection + /// Attribute to remove + /// FileAttributes after update + /// True if attributes updated + public static bool TryRemoveFileAttrribute(FileAttributes source, FileAttributes attr, out FileAttributes updatedSource) + { + if (ContainsFileAttribute(source, attr)) + { + updatedSource = source; + return false; + } + + updatedSource = RemoveFileAttribute(source, attr); + return true; + } + + /// + /// Removes a to the existing collection . + /// + /// collection + /// Attribute to remove + /// + public static FileAttributes RemoveFileAttribute(FileAttributes source, FileAttributes attr) + { + source &= attr; + return source; + } + + /// + /// Checks whether the given attribute in the collection is included. + /// + /// collection + /// Attribute to check + /// True if exists, false if not + public static bool ContainsFileAttribute(FileAttributes source, FileAttributes attr) + { + return (source & attr) != 0; + } +} diff --git a/src/QuickIO/InvalidPathException.cs b/src/QuickIO/InvalidPathException.cs new file mode 100644 index 0000000..e4d4e0f --- /dev/null +++ b/src/QuickIO/InvalidPathException.cs @@ -0,0 +1,29 @@ +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +/// +/// Invalid Path Exception +/// +[Serializable] +public class InvalidPathException : QuickIOBaseException +{ + /// + /// Invalid Path Exception + /// + /// Invalid Path + public InvalidPathException(string path) + : base(Win32ErrorCodes.FormatMessage(Win32ErrorCodes.ERROR_INVALID_NAME), path) + { + } + + /// + /// Invalid Path Exception + /// + /// Error Message + /// Invalid Path + public InvalidPathException(string message, string path) + : base(message, path) + { + } +} diff --git a/src/QuickIO/License.txt b/src/QuickIO/License.txt new file mode 100644 index 0000000..f085b8e --- /dev/null +++ b/src/QuickIO/License.txt @@ -0,0 +1,22 @@ +QuickIO.NET is published under Microsoft Public License (Ms-PL) +http://quickIO.NET + +http://www.microsoft.com/en-us/openness/licenses.aspx +Microsoft Public License (Ms-PL) + +This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. + +Definitions +The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. +A "contribution" is the original software, or any additions or changes to the software. +A "contributor" is any person that distributes its contribution under this license. +"Licensed patents" are a contributor's patent claims that read directly on its contribution. +Grant of Rights +(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. +(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. +Conditions and Limitations +(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. +(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. +(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. +(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. +(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees, or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. \ No newline at end of file diff --git a/src/QuickIO/Overrides/DirectoryInfo.cs b/src/QuickIO/Overrides/DirectoryInfo.cs new file mode 100644 index 0000000..3aae5f3 --- /dev/null +++ b/src/QuickIO/Overrides/DirectoryInfo.cs @@ -0,0 +1,5 @@ +namespace SchwabenCode.QuickIO.Overrides; + +internal class DirectoryInfo +{ +} diff --git a/src/QuickIO/Overrides/FileInfo.cs b/src/QuickIO/Overrides/FileInfo.cs new file mode 100644 index 0000000..c4b2076 --- /dev/null +++ b/src/QuickIO/Overrides/FileInfo.cs @@ -0,0 +1,5 @@ +namespace SchwabenCode.QuickIO.Overrides; + +internal class FileInfo +{ +} diff --git a/src/QuickIO/PathAlreadyExistsException.cs b/src/QuickIO/PathAlreadyExistsException.cs new file mode 100644 index 0000000..e4cd848 --- /dev/null +++ b/src/QuickIO/PathAlreadyExistsException.cs @@ -0,0 +1,20 @@ +using System.Diagnostics.Contracts; + +namespace SchwabenCode.QuickIO; + +/// +/// Exception if path does not exist. +/// +[Serializable] +public class PathAlreadyExistsException : QuickIOBaseException +{ + /// + /// Exception if path does not exist. + /// + public PathAlreadyExistsException(string message, string path) + : base(message, path) + { + Contract.Requires(!string.IsNullOrWhiteSpace(message)); + Contract.Requires(!string.IsNullOrWhiteSpace(path)); + } +} diff --git a/src/QuickIO/PathNotFoundException.cs b/src/QuickIO/PathNotFoundException.cs new file mode 100644 index 0000000..8690b4b --- /dev/null +++ b/src/QuickIO/PathNotFoundException.cs @@ -0,0 +1,26 @@ +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +/// +/// Exception if path does not exist. +/// +[Serializable] +public class PathNotFoundException : QuickIOBaseException +{ + /// + /// Exception if path does not exist. + /// + public PathNotFoundException(string path) + : base(Win32ErrorCodes.FormatMessage(Win32ErrorCodes.ERROR_PATH_NOT_FOUND), path) + { + } + + /// + /// Exception if path does not exist. + /// + public PathNotFoundException(string message, string path) + : base(message, path) + { + } +} diff --git a/src/QuickIO/QuickIO.cs b/src/QuickIO/QuickIO.cs new file mode 100644 index 0000000..289d139 --- /dev/null +++ b/src/QuickIO/QuickIO.cs @@ -0,0 +1,305 @@ +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +/// +/// Provides static methods for files and directories. +/// +[Obsolete("It's recommended to use the QuickIOFile, QuickIODirectory classes")] +public static partial class QuickIO +{ + /// + /// Checks whether a file exists + /// + /// File path to check + /// + /// Searched for file but found folder. + /// Path is invalid. + public static bool FileExists(string path) + { + return QuickIOFile.Exists(path); + } + + /// + /// Checks whether a file exists + /// + /// File path to check + /// + /// Searched for file but found folder. + /// Path is invalid. + public static bool FileExists(QuickIOPathInfo pathInfo) + { + return QuickIOFile.Exists(pathInfo); + } + + /// + /// Checks whether a directory exists + /// + /// Directory path to verify + /// + /// Searched for directory but found file. + /// Path is invalid. + public static bool DirectoryExists(string path) + { + return QuickIODirectory.Exists(path); + } + + /// + /// Checks whether a directory exists + /// + /// Directory path to verify + /// + /// Searched for directory but found file. + /// Path is invalid. + public static bool DirectoryExists(QuickIOPathInfo pathInfo) + { + return QuickIODirectory.Exists(pathInfo); + } + + /// + /// Creates a new file. + /// + /// The path to the file. + /// - default + /// - default + /// - default + /// - default 0 (none) + /// The specified path already exists. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + public static void CreateFile(string path, FileAccess fileAccess = FileAccess.Write, FileShare fileShare = FileShare.None, FileMode fileMode = FileMode.Create, FileAttributes fileAttributes = 0) + { + QuickIOFile.Create(new QuickIOPathInfo(path), fileAccess, fileShare, fileMode, fileAttributes); + } + + /// + /// Creates a new directory. If is false, the parent directory must exist. + /// + /// The path to the directory. + /// If is false, the parent directory must exist. + /// Path already exists. + /// The directory is not empty. + public static void CreateDirectory(string path, bool recursive = false) + { + QuickIODirectory.Create(new QuickIOPathInfo(path), recursive); + } + + /// + /// Removes a file. + /// + /// The path to the file. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// File does not exist. + public static void DeleteFile(string path) + { + InternalQuickIO.DeleteFile(new QuickIOPathInfo(path)); + } + + /// + /// Removes a file. + /// + /// The file. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// File does not exist. + public static void DeleteFile(QuickIOPathInfo pathInfo) + { + InternalQuickIO.DeleteFile(pathInfo); + } + + /// + /// Removes a file. + /// + /// The file. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// File does not exist. + public static void DeleteFile(QuickIOFileInfo file) + { + InternalQuickIO.DeleteFile(file); + } + + /// + /// Removes a directory. + /// + /// The path to the directory. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// The directory is not empty. + public static void DeleteDirectory(string path) + { + DeleteDirectory(new QuickIOPathInfo(path)); + } + + /// + /// Removes a directory. + /// + /// The path of the directory. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// The directory is not empty. + public static void DeleteDirectory(QuickIOPathInfo pathInfo) + { + InternalQuickIO.DeleteDirectory(pathInfo); + } + + /// + /// Removes a directory. + /// + /// The directory. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// The directory is not empty. + public static void DeleteDirectory(QuickIODirectoryInfo directoryInfo) + { + DeleteDirectory(directoryInfo.PathInfo); + } + + /// + /// Returns a file list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a file list from the current directory + public static IEnumerable EnumerateFiles(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return QuickIODirectory.EnumerateFiles(new QuickIOPathInfo(path), pattern, searchOption); + } + + /// + /// Returns a file list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a file list from the current directory + public static IEnumerable EnumerateFiles(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return QuickIODirectory.EnumerateFiles(pathInfo, pattern, searchOption); + } + + /// + /// Returns a file list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a file list from the current directory + public static IEnumerable EnumerateFiles(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return QuickIODirectory.EnumerateFiles(directoryInfo, pattern, searchOption); + } + + /// + /// Returns a file path list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a file path list from the current directory + public static IEnumerable EnumerateFilePaths(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return QuickIODirectory.EnumerateFilePaths(path, pattern, searchOption); + } + + /// + /// Returns a file path list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a file path list from the current directory + public static IEnumerable EnumerateFilePaths(QuickIOPathInfo path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return QuickIODirectory.EnumerateFilePaths(path, pattern, searchOption); + } + + /// + /// Returns a file path list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a file path list from the current directory + public static IEnumerable EnumerateFilePaths(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return QuickIODirectory.EnumerateFilePaths(directoryInfo, pattern, searchOption); + } + + /// + /// Returns a directory list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a directory list from the current directory + public static IEnumerable EnumerateDirectories(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return QuickIODirectory.EnumerateDirectories(new QuickIOPathInfo(path), pattern, searchOption); + } + + /// + /// Returns a directory list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a directory list from the current directory + public static IEnumerable EnumerateDirectories(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return QuickIODirectory.EnumerateDirectories(pathInfo, pattern, searchOption); + } + + /// + /// Returns a directory list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a directory list from the current directory + public static IEnumerable EnumerateDirectories(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return QuickIODirectory.EnumerateDirectories(directoryInfo, pattern, searchOption); + } + + /// + /// Returns a directory path list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a directory path list from the current directory + public static IEnumerable EnumerateDirectoryPaths(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return QuickIODirectory.EnumerateDirectoryPaths(path, pattern, searchOption); + } + + /// + /// Returns a directory path list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a directory path list from the current directory + public static IEnumerable EnumerateDirectoryPaths(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return QuickIODirectory.EnumerateDirectoryPaths(pathInfo, pattern, searchOption); + } + + /// + /// Returns a directory path list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a directory path list from the current directory + public static IEnumerable EnumerateDirectoryPaths(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return QuickIODirectory.EnumerateDirectoryPaths(directoryInfo, pattern, searchOption); + } + + /// + /// Receives of specifies path + /// + /// + /// See http://support.microsoft.com/kb/231497 + public static QuickIODiskInformation GetDiskInformation(string path) + { + return InternalQuickIO.GetDiskInformation(path); + } +} diff --git a/src/QuickIO/QuickIO.csproj b/src/QuickIO/QuickIO.csproj new file mode 100644 index 0000000..2d28999 --- /dev/null +++ b/src/QuickIO/QuickIO.csproj @@ -0,0 +1,183 @@ + + + + + TextTemplatingFileGenerator + SaveOutput.cs + + + TextTemplatingFileGenerator + StaticAttributeMethods.cs + + + TextTemplatingFileGenerator + StaticAttributeMethods_Async.cs + + + TextTemplatingFileGenerator + StaticFileTimeMethods.cs + + + TextTemplatingFileGenerator + StaticFileTimeMethods_Async.cs + + + TextTemplatingFileGenerator + StaticRootMethods.cs + + + TextTemplatingFileGenerator + StaticRootMethods_Async.cs + + + TextTemplatingFileGenerator + QuickIODirectory_Attributes.cs + + + TextTemplatingFileGenerator + QuickIODirectory_Attributes_Async.cs + + + TextTemplatingFileGenerator + QuickIODirectory_FileTime.cs + + + TextTemplatingFileGenerator + QuickIODirectory_FileTime_Async.cs + + + TextTemplatingFileGenerator + QuickIODirectory_Root.cs + + + TextTemplatingFileGenerator + QuickIODirectory_Root_Async.cs + + + TextTemplatingFileGenerator + QuickIOFile_Attributes.cs + + + TextTemplatingFileGenerator + QuickIOFile_Attributes_Async.cs + + + TextTemplatingFileGenerator + QuickIOFile_FileTime.cs + + + TextTemplatingFileGenerator + QuickIOFile_FileTime_Async.cs + + + TextTemplatingFileGenerator + QuickIOFile_Root.cs + + + TextTemplatingFileGenerator + QuickIOFile_Root_Async.cs + + + + + + True + True + SaveOutput.tt + + + True + True + StaticAttributeMethods.tt + + + True + True + StaticAttributeMethods_Async.tt + + + True + True + StaticFileTimeMethods.tt + + + True + True + StaticFileTimeMethods_Async.tt + + + True + True + StaticRootMethods.tt + + + True + True + StaticRootMethods_Async.tt + + + True + True + QuickIODirectory_Attributes.tt + + + True + True + QuickIODirectory_Attributes_Async.tt + + + True + True + QuickIODirectory_FileTime.tt + + + True + True + QuickIODirectory_FileTime_Async.tt + + + True + True + QuickIODirectory_Root.tt + + + True + True + QuickIODirectory_Root_Async.tt + + + True + True + QuickIOFile_Attributes.tt + + + True + True + QuickIOFile_Attributes_Async.tt + + + True + True + QuickIOFile_FileTime.tt + + + True + True + QuickIOFile_FileTime_Async.tt + + + True + True + QuickIOFile_Root.tt + + + True + True + QuickIOFile_Root_Async.tt + + + + + + + diff --git a/src/QuickIO/QuickIOBaseException.cs b/src/QuickIO/QuickIOBaseException.cs new file mode 100644 index 0000000..8e3045f --- /dev/null +++ b/src/QuickIO/QuickIOBaseException.cs @@ -0,0 +1,34 @@ +using System.ComponentModel; + +namespace SchwabenCode.QuickIO; + +/// +/// Abstract base class for exceptions +/// +[Browsable(false)] +[EditorBrowsable(EditorBrowsableState.Never)] +public abstract class QuickIOBaseException : Exception +{ + /// + /// Affected Path + /// + public string Path { get; private set; } + + /// + /// Abstract base class for exceptions + /// + protected QuickIOBaseException(string message, string path) + : base(message) + { + Path = path; + } + + /// + /// Abstract base class for exceptions + /// + protected QuickIOBaseException(string message, string path, Exception innerException) + : base(message, innerException) + { + Path = path; + } +} diff --git a/src/QuickIO/QuickIODirectoryInfo.cs b/src/QuickIO/QuickIODirectoryInfo.cs new file mode 100644 index 0000000..65222c7 --- /dev/null +++ b/src/QuickIO/QuickIODirectoryInfo.cs @@ -0,0 +1,71 @@ +using SchwabenCode.QuickIO.Internal; +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +/// +/// Provides properties and instance methods for directories +/// +public sealed partial class QuickIODirectoryInfo : QuickIOFileSystemEntryBase +{ + /// + /// Create new instance of + /// + public QuickIODirectoryInfo(string path) + : this(new QuickIOPathInfo(path)) { } + + /// + /// Create new instance of + /// + public QuickIODirectoryInfo(DirectoryInfo directoryInfo) + : this(new QuickIOPathInfo(directoryInfo.FullName)) { } + + /// + /// Create new instance of + /// + public QuickIODirectoryInfo(QuickIOPathInfo pathInfo) + : this(pathInfo, pathInfo.IsRoot ? null : InternalQuickIO.GetFindDataFromPath(pathInfo)) + { + } + + /// + /// Creates the folder information on the basis of the path and the handles + /// + /// + /// + internal QuickIODirectoryInfo(QuickIOPathInfo pathInfo, Win32FindData? win32FindData) + : base(pathInfo, win32FindData) + { + if (win32FindData is not null) + { + LastWriteTimeUtc = win32FindData.GetLastWriteTimeUtc(); + LastAccessTimeUtc = win32FindData.GetLastAccessTimeUtc(); + CreationTimeUtc = win32FindData.GetCreationTimeUtc(); + } + } + + /// + /// Creates the folder information on the basis of the path and the handles + /// + /// Full path to the directory + /// + internal QuickIODirectoryInfo(string fullname, Win32FindData? win32FindData) + : this(new QuickIOPathInfo(fullname), win32FindData) { } + + /// + /// Returns true if current path is root + /// + public bool IsRoot { get { return PathInfo.IsRoot; } } + + /// + /// Returns true if directory exists. Result starts a file system call and is not cached. + /// + /// Path exists but it's a file.. + public override bool Exists + { + get + { + return QuickIODirectory.Exists(this); + } + } +} diff --git a/src/QuickIO/QuickIODirectoryInfo_Async.cs b/src/QuickIO/QuickIODirectoryInfo_Async.cs new file mode 100644 index 0000000..02fbad3 --- /dev/null +++ b/src/QuickIO/QuickIODirectoryInfo_Async.cs @@ -0,0 +1,20 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Provides properties and instance methods for directories +/// +public sealed partial class QuickIODirectoryInfo +{ + + /// + /// Returns true if directory exists. Result starts a file system call and is not cached. + /// + /// Path exists but it's a file.. + public override Task ExistsAsync + { + get + { + return QuickIODirectory.ExistsAsync(this); + } + } +} diff --git a/src/QuickIO/QuickIODirectoryInfo_Enumerations.cs b/src/QuickIO/QuickIODirectoryInfo_Enumerations.cs new file mode 100644 index 0000000..917e095 --- /dev/null +++ b/src/QuickIO/QuickIODirectoryInfo_Enumerations.cs @@ -0,0 +1,98 @@ +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIODirectoryInfo +{ + #region EnumerateDirectoryPaths + + /// + /// Returns an enumerable collection of directory names. + /// + /// Search pattern. Uses Win32 native filtering. + /// Specifiy depth with + /// Type of return + /// Options + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + public IEnumerable EnumerateDirectoryPaths(string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return QuickIODirectory.EnumerateDirectoryPaths(PathInfo, pattern, searchOption, pathFormatReturn, enumerateOptions); + } + + #endregion + + #region EnumerateDirectories + + /// + /// Returns an enumerable collection of directories in a specified path. + /// + /// Search pattern. Uses Win32 native filtering. + /// Specifiy depth with + /// Options + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + public IEnumerable EnumerateDirectories(string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return QuickIODirectory.EnumerateDirectories(PathInfo, pattern, searchOption, enumerateOptions); + } + #endregion + + #region EnumerateFilePaths + + /// + /// Returns an enumerable collection of file names in a specified path. + /// + /// Search pattern. Uses Win32 native filtering. + /// Specifiy depth with + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + public IEnumerable EnumerateFilePaths(string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return QuickIODirectory.EnumerateFilePaths(PathInfo, pattern, searchOption, pathFormatReturn, enumerateOptions); + } + + #endregion + + #region EnumerateFiles + /// + /// Returns an enumerable collection of files in a specified path. + /// + /// Search pattern. Uses Win32 native filtering. + /// Specifiy depth with + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + public IEnumerable EnumerateFiles(string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return QuickIODirectory.EnumerateFiles(PathInfo, pattern, searchOption); + } + + #endregion + + #region EnumerateFileSystemEntryPaths + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories. + /// + /// Search pattern. Uses Win32 native filtering. + /// Specifiy depth with + /// Options + /// Type of return + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public IEnumerable> EnumerateFileSystemEntryPaths(string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return QuickIODirectory.EnumerateFileSystemEntryPaths(PathInfo, pattern, searchOption, pathFormatReturn, enumerateOptions); + } + #endregion + + #region EnumerateFileSystemEntries + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories. + /// + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// Options + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + public IEnumerable> EnumerateFileSystemEntries(string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return QuickIODirectory.EnumerateFileSystemEntries(PathInfo, pattern, searchOption); + } + #endregion +} diff --git a/src/QuickIO/QuickIODirectoryInfo_Enumerations_Async.cs b/src/QuickIO/QuickIODirectoryInfo_Enumerations_Async.cs new file mode 100644 index 0000000..b34fde2 --- /dev/null +++ b/src/QuickIO/QuickIODirectoryInfo_Enumerations_Async.cs @@ -0,0 +1,88 @@ +using SchwabenCode.QuickIO.Compatibility; + + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIODirectoryInfo +{ + /// + /// Returns an enumerable collection of directory names in a seperate task created by the default . + /// + /// Search pattern. Uses Win32 native filtering. + /// Specifiy depth with + /// Options + /// Type of return + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public Task> EnumerateDirectoryPathsAsync(string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectoryPaths(pattern, searchOption, pathFormatReturn, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of directories in a specified path in a seperate task created by the default . + /// + /// Search pattern. Uses Win32 native filtering. + /// Specifiy depth with + /// Options + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public Task> EnumerateDirectoriesAsync(string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectories(pattern, searchOption, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of file names in a specified path in a seperate task created by the default . + /// + /// Search pattern. Uses Win32 native filtering. + /// Specifiy depth with + /// Type of return + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public Task> EnumerateFilePathsAsync(string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFilePaths(pattern, searchOption, pathFormatReturn, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of files in a specified path in a seperate task created by the default . + /// + /// Search pattern. Uses Win32 native filtering. + /// Specifiy depth with + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public Task> EnumerateFilesAsync(string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFiles(pattern, searchOption, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories in a seperate task created by the default . + /// + /// Search pattern. Uses Win32 native filtering. + /// Specifiy depth with + /// Options + /// Type of return + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public Task>> EnumerateFileSystemEntryPathsAsync(string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFileSystemEntryPaths(pattern, searchOption, pathFormatReturn, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories in a seperate task created by the default . + /// + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// Options + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public Task>> EnumerateFileSystemEntriesAsync(string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFileSystemEntries(pattern, searchOption, enumerateOptions)); + } +} diff --git a/src/QuickIO/QuickIODirectoryInfo_Metadata.cs b/src/QuickIO/QuickIODirectoryInfo_Metadata.cs new file mode 100644 index 0000000..46549b1 --- /dev/null +++ b/src/QuickIO/QuickIODirectoryInfo_Metadata.cs @@ -0,0 +1,19 @@ +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIODirectoryInfo +{ + /// + /// Receives of current file + /// + /// + public QuickIODirectoryMetadata? GetMetadata(QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + if (FindData is null) + { + return null; + } + return InternalQuickIO.EnumerateDirectoryMetadata(FullNameUnc, FindData, enumerateOptions); + } +} diff --git a/src/QuickIO/QuickIODirectoryInfo_Metadata_Async.cs b/src/QuickIO/QuickIODirectoryInfo_Metadata_Async.cs new file mode 100644 index 0000000..de178d6 --- /dev/null +++ b/src/QuickIO/QuickIODirectoryInfo_Metadata_Async.cs @@ -0,0 +1,13 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIODirectoryInfo +{ + /// + /// Receives of current file + /// + /// + public Task GetMetadataAsync(QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + => NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetMetadata(enumerateOptions)); +} diff --git a/src/QuickIO/QuickIODirectoryInfo_Operators.cs b/src/QuickIO/QuickIODirectoryInfo_Operators.cs new file mode 100644 index 0000000..50c4631 --- /dev/null +++ b/src/QuickIO/QuickIODirectoryInfo_Operators.cs @@ -0,0 +1,24 @@ +using SchwabenCode.QuickIO.Internal; +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIODirectoryInfo +{ + /// + /// Returns a of the current path of this folder + /// + /// + public DirectoryInfo AsDirectoryInfo() + { + return new DirectoryInfo(base.FullName); + } + + /// + /// Explizit Cast + /// + /// + /// + public static explicit operator QuickIODirectoryInfo(DirectoryInfo directoryInfo) + { + return InternalQuickIO.LoadDirectoryFromPathInfo(new QuickIOPathInfo(directoryInfo.FullName)); + } +} diff --git a/src/QuickIO/QuickIODirectoryInfo_Operators_Async.cs b/src/QuickIO/QuickIODirectoryInfo_Operators_Async.cs new file mode 100644 index 0000000..ad2eb46 --- /dev/null +++ b/src/QuickIO/QuickIODirectoryInfo_Operators_Async.cs @@ -0,0 +1,15 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIODirectoryInfo +{ + /// + /// Returns a of the current path of this folder + /// + /// + public Task AsDirectoryInfoAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(AsDirectoryInfo); + } +} diff --git a/src/QuickIO/QuickIODirectoryMetadata.cs b/src/QuickIO/QuickIODirectoryMetadata.cs new file mode 100644 index 0000000..d42bc00 --- /dev/null +++ b/src/QuickIO/QuickIODirectoryMetadata.cs @@ -0,0 +1,81 @@ +using System.Collections.ObjectModel; +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +/// +/// Directory metadata information +/// +public sealed partial class QuickIODirectoryMetadata : QuickIOFileSystemMetadataBase +{ + /// + /// Creates instance of + /// + /// Win32FindData of current directory + /// Directories in current directory + /// Files in current directory + /// UNC Path of current directory + internal QuickIODirectoryMetadata(string uncFullname, Win32FindData win32FindData, IList subDirs, IList subFiles) + : base(uncFullname, win32FindData) + { + Directories = new ReadOnlyCollection(subDirs); + Files = new ReadOnlyCollection(subFiles); + } + + /// + /// Directories in current directory + /// + public ReadOnlyCollection Directories { get; internal set; } + + /// + /// Files in current directory + /// + public ReadOnlyCollection Files { get; internal set; } + + private ulong? _bytes; + /// + /// Size of the file. + /// + public ulong Bytes + { + get + { + if (_bytes == null) + { + ulong bytes = 0; + + #region Dirs + + { + for (int i = 0; i < Directories.Count; i++) + { + bytes += +Directories[i].Bytes; + } + } + + #endregion + + #region Files + { + for (int i = 0; i < Files.Count; i++) + { + bytes += +Files[i].Bytes; + } + } + #endregion + + _bytes = bytes; + } + return (ulong)_bytes; + } + } + + /// + /// Returns a new instance of of the current directory + /// + /// + public QuickIODirectoryInfo ToDirectoryInfo() + { + return new QuickIODirectoryInfo(ToPathInfo()); + } +} diff --git a/src/QuickIO/QuickIODirectoryMetadata_Async.cs b/src/QuickIO/QuickIODirectoryMetadata_Async.cs new file mode 100644 index 0000000..9a4c5a8 --- /dev/null +++ b/src/QuickIO/QuickIODirectoryMetadata_Async.cs @@ -0,0 +1,15 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIODirectoryMetadata +{ + /// + /// Returns a new instance of of the current directory + /// + /// + public Task ToDirectoryInfoAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(ToDirectoryInfo); + } +} diff --git a/src/QuickIO/QuickIODirectory_Attributes.cs b/src/QuickIO/QuickIODirectory_Attributes.cs new file mode 100644 index 0000000..b88daca --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Attributes.cs @@ -0,0 +1,135 @@ +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIODirectory +{ + /// + /// Gets the of the directory or file. + /// + /// The path to the directory or file. + /// New attributes to set. + /// The of the directory or file. + public static void SetAttributes(string path, FileAttributes attributes) + { + SetAttributes(new QuickIOPathInfo(path), attributes); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// New attributes to set. + /// The of the directory or file. + public static void SetAttributes(QuickIOPathInfo info, FileAttributes attributes) + { + InternalQuickIO.SetAttributes(info, attributes); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// New attributes to set. + /// The of the directory or file. + public static void SetAttributes(QuickIODirectoryInfo info, FileAttributes attributes) + { + InternalQuickIO.SetAttributes(info.PathInfo, attributes); + } + + /// + /// Gets the of the directory or file. + /// + /// The path to the directory or file. + /// The of the directory or file. + public static FileAttributes GetAttributes(string path) + { + return GetAttributes(new QuickIOPathInfo(path)); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// The of the directory or file. + public static FileAttributes GetAttributes(QuickIOPathInfo info) + { + return InternalQuickIO.GetAttributes(info); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// The of the directory or file. + public static FileAttributes GetAttributes(QuickIODirectoryInfo info) + { + return InternalQuickIO.GetAttributes(info.PathInfo); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static bool RemoveAttribute(string path, FileAttributes attribute) + { + return RemoveAttribute(new QuickIOPathInfo(path), attribute); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static bool RemoveAttribute(QuickIOPathInfo info, FileAttributes attribute) + { + return InternalQuickIO.RemoveAttribute(info, attribute); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static bool RemoveAttribute(QuickIODirectoryInfo info, FileAttributes attribute) + { + return InternalQuickIO.RemoveAttribute(info.PathInfo, attribute); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static bool AddAttribute(string path, FileAttributes attribute) + { + return AddAttribute(new QuickIOPathInfo(path), attribute); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static bool AddAttribute(QuickIOPathInfo info, FileAttributes attribute) + { + return InternalQuickIO.AddAttribute(info, attribute); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static bool AddAttribute(QuickIODirectoryInfo info, FileAttributes attribute) + { + return InternalQuickIO.AddAttribute(info.PathInfo, attribute); + } +} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.Root.tt b/src/QuickIO/QuickIODirectory_Attributes.tt similarity index 51% rename from src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.Root.tt rename to src/QuickIO/QuickIODirectory_Attributes.tt index 8c9a5c1..11b774f 100644 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.Root.tt +++ b/src/QuickIO/QuickIODirectory_Attributes.tt @@ -1,6 +1,6 @@ <#@ template language="C#" hostspecific="true" #> -<#@ include file="..\Templates\SaveOutput.tt" #> -<#@ include file="..\Templates\StaticRootMethods.tt" #> +<#@ include file=".\CodeTemplates\SaveOutput.tt" #> +<#@ include file=".\CodeTemplates\StaticAttributeMethods.tt" #> <#@ output extension=".cs" #> <# Generate("QuickIODirectory"); diff --git a/src/QuickIO/QuickIODirectory_Attributes_Async.cs b/src/QuickIO/QuickIODirectory_Attributes_Async.cs new file mode 100644 index 0000000..412dda8 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Attributes_Async.cs @@ -0,0 +1,135 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIODirectory +{ + /// + /// Gets the of the directory or file. + /// + /// The path to the directory or file. + /// New attributes to set. + /// The of the directory or file. + public static Task SetAttributesAsync(string path, FileAttributes attributes) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetAttributes(path, attributes)); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// New attributes to set. + /// The of the directory or file. + public static Task SetAttributesAsync(QuickIOPathInfo info, FileAttributes attributes) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetAttributes(info, attributes)); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// New attributes to set. + /// The of the directory or file. + public static Task SetAttributesAsync(QuickIODirectoryInfo info, FileAttributes attributes) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetAttributes(info.PathInfo, attributes)); + } + + /// + /// Gets the of the directory or file. + /// + /// The path to the directory or file. + /// The of the directory or file. + public static Task GetAttributesAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetAttributes(path)); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// The of the directory or file. + public static Task GetAttributesAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetAttributes(info)); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// The of the directory or file. + public static Task GetAttributesAsync(QuickIODirectoryInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetAttributes(info)); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static Task RemoveAttributeAsync(string path, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.RemoveAttribute(path, attribute)); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static Task RemoveAttributeAsync(QuickIOPathInfo info, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.RemoveAttribute(info, attribute)); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static Task RemoveAttributeAsync(QuickIODirectoryInfo info, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.RemoveAttribute(info, attribute)); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static Task AddAttributeAsync(string path, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.AddAttribute(path, attribute)); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static Task AddAttributeAsync(QuickIOPathInfo info, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.AddAttribute(info, attribute)); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static Task AddAttributeAsync(QuickIODirectoryInfo info, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.AddAttribute(info, attribute)); + } +} diff --git a/src/QuickIO/QuickIODirectory_Attributes_Async.tt b/src/QuickIO/QuickIODirectory_Attributes_Async.tt new file mode 100644 index 0000000..0d20dd7 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Attributes_Async.tt @@ -0,0 +1,7 @@ +<#@ template language="C#" hostspecific="true" #> +<#@ include file=".\CodeTemplates\SaveOutput.tt" #> +<#@ include file=".\CodeTemplates\StaticAttributeMethods_Async.tt" #> +<#@ output extension=".cs" #> +<# + Generate("QuickIODirectory"); +#> \ No newline at end of file diff --git a/src/QuickIO/QuickIODirectory_Compress.cs b/src/QuickIO/QuickIODirectory_Compress.cs new file mode 100644 index 0000000..77c59d2 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Compress.cs @@ -0,0 +1,52 @@ +using System.IO.Compression; +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIODirectory +{ + /// + /// Compresses a directory by using + /// ZipFile.CreateFromDirectory + /// + /// + /// Directory fullname to zip + /// Zipfile fullname to save + /// true to overwrite existing zipfile + /// + /// True to include basedirectory + public static void Compress(String directoryFullPath, String zipFullPath, bool overWriteExistingZip = false, CompressionLevel compressionLevel = CompressionLevel.Fastest, bool includeBaseDirectory = false) + { + Invariant.NotEmpty(directoryFullPath); + Invariant.NotEmpty(zipFullPath); + + if (!Exists(directoryFullPath)) + { + throw new DirectoryNotFoundException("Directory to zip '" + directoryFullPath + "' does not exist."); + } + + if (!overWriteExistingZip && (QuickIOFile.Exists(zipFullPath))) + { + throw new FileAlreadyExistsException("The target zipFile name '" + zipFullPath + "' already exists.", zipFullPath); + } + + ZipFile.CreateFromDirectory(directoryFullPath, zipFullPath, compressionLevel, includeBaseDirectory); + } + + /// + /// Compresses a directory by using + /// ZipFile.CreateFromDirectory + /// + /// + /// Directory to zip + /// Zipfile fullname to save + /// true to overwrite existing zipfile + /// + /// True to include basedirectory + public static void Compress(QuickIODirectoryInfo directory, String zipFullPath, bool overWriteExistingZip = false, CompressionLevel compressionLevel = CompressionLevel.Fastest, bool includeBaseDirectory = false) + { + Invariant.NotEmpty(zipFullPath); + + Compress(directory.FullName, zipFullPath, overWriteExistingZip, compressionLevel, includeBaseDirectory); + } +} diff --git a/src/QuickIO/QuickIODirectory_Compress_Async.cs b/src/QuickIO/QuickIODirectory_Compress_Async.cs new file mode 100644 index 0000000..f6872b9 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Compress_Async.cs @@ -0,0 +1,37 @@ +using System.IO.Compression; +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIODirectory +{ + /// + /// Compresses a directory by using + /// ZipFile.CreateFromDirectory + /// + /// + /// Directory fullname to zip + /// Zipfile fullname to save + /// true to overwrite existing zipfile + /// + /// True to include basedirectory + public static Task CompressAsync(String directoryFullPath, String zipFullPath, bool overWriteExistingZip = false, CompressionLevel compressionLevel = CompressionLevel.Fastest, bool includeBaseDirectory = false) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Compress(directoryFullPath, zipFullPath, overWriteExistingZip, compressionLevel, includeBaseDirectory)); + } + + /// + /// Compresses a directory by using + /// ZipFile.CreateFromDirectory + /// + /// + /// Directory to zip + /// Zipfile fullname to save + /// true to overwrite existing zipfile + /// + /// True to include basedirectory + public static Task CompressAsync(QuickIODirectoryInfo directory, String zipFullPath, bool overWriteExistingZip = false, CompressionLevel compressionLevel = CompressionLevel.Fastest, bool includeBaseDirectory = false) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Compress(directory, zipFullPath, overWriteExistingZip, compressionLevel, includeBaseDirectory)); + } +} diff --git a/src/QuickIO/QuickIODirectory_Copy.cs b/src/QuickIO/QuickIODirectory_Copy.cs new file mode 100644 index 0000000..2f8bc19 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Copy.cs @@ -0,0 +1,66 @@ +using SchwabenCode.QuickIO.Internal; +namespace SchwabenCode.QuickIO; + +public static partial class QuickIODirectory +{ + /// + /// Copies a directory and all contents + /// + /// Source directory + /// Target directory + /// true to overwrite existing files + /// Cancallation Token + public static void Copy(string source, string target, bool overwrite = false, CancellationToken cancellationToken = default) + { + Copy(new QuickIODirectoryInfo(source), new QuickIOPathInfo(target), overwrite, cancellationToken); + } + + /// + /// Copies a directory and all contents + /// + /// Source directory + /// Target directory + /// true to overwrite existing files + /// Cancallation Token + public static void Copy(QuickIODirectoryInfo source, QuickIOPathInfo target, bool overwrite = false, CancellationToken cancellationToken = default) + { + IEnumerable> allContentUncPaths = EnumerateFileSystemEntryPaths( source, QuickIOPatternConstants.All, SearchOption.AllDirectories, QuickIOPathType.UNC ); + foreach (KeyValuePair entry in allContentUncPaths) + { + cancellationToken.ThrowIfCancellationRequested(); + string sourcePathUnc = entry.Key; + string targetFullnameUnc = target.FullNameUnc + sourcePathUnc.Substring( source.FullNameUnc.Length ); + + if (!QuickIODirectory.Exists(targetFullnameUnc)) + { + + } + + switch (entry.Value) + { + case QuickIOFileSystemEntryType.Directory: + { + QuickIODirectory.Create(targetFullnameUnc, true); + } + break; + + case QuickIOFileSystemEntryType.File: + { + QuickIOFile.Copy(sourcePathUnc, targetFullnameUnc, overwrite); + } + break; + } + } + } + + + /// + /// Receives of current directory using a sperare Task + /// + /// + public static Task GetMetadastaAsync(string directoryPath) + { + return Compatibility.NETCompatibility.AsyncExtensions + .GetAsyncResult(() => InternalQuickIO.EnumerateDirectoryMetadata(new QuickIOPathInfo(directoryPath))); + } +} diff --git a/src/QuickIO/QuickIODirectory_Copy_Async.cs b/src/QuickIO/QuickIODirectory_Copy_Async.cs new file mode 100644 index 0000000..b7dee5b --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Copy_Async.cs @@ -0,0 +1,36 @@ +using SchwabenCode.QuickIO.Compatibility; +namespace SchwabenCode.QuickIO; + +public static partial class QuickIODirectory +{ + /// + /// Copies a directory and all contents + /// + /// Source directory + /// Target directory + /// true to overwrite existing files + public static Task CopyAsync(string source, string target, bool overwrite = false +, CancellationToken cancellationToken = default +) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Copy(source, target, overwrite +, cancellationToken +)); + } + + /// + /// Copies a directory and all contents + /// + /// Source directory + /// Target directory + /// true to overwrite existing files + public static Task CopyAsync(QuickIODirectoryInfo source, QuickIOPathInfo target, bool overwrite = false +, CancellationToken cancellationToken = default + ) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Copy(source, target, overwrite +, cancellationToken + )); + } + +} diff --git a/src/QuickIO/QuickIODirectory_Create.cs b/src/QuickIO/QuickIODirectory_Create.cs new file mode 100644 index 0000000..0c4f319 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Create.cs @@ -0,0 +1,89 @@ +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIODirectory +{ + /// + /// Creates a new directory. If is false, the parent directory must exist. + /// + /// The path to the directory. + /// If is false, the parent directory must exist. + /// http://msdn.microsoft.com/en-us/library/54a0at6s(v=vs.110).aspx + /// The specified path already exists. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// + /// Creates directory structure + /// + /// public static void Create_With_StringPath_Example() + /// { + /// // Creates directory C:\temp\QuickIOTest\sub\folder\tree and all not existing parent folders + /// QuickIODirectory.Create( @"C:\temp\QuickIOTest\sub\folder\tree", recursive: true ); + /// } + /// + /// + /// + /// Shows how to handle sample exception if parent directory does not exist. + /// + /// public static void Create_With_StringPath_Example() + /// { + /// try + /// { + /// QuickIODirectory.Create( @"C:\temp\QuickIOTest\sub\folder\tree", recursive: false ); + /// } + /// catch ( PathNotFoundException pathNotFoundException ) + /// { + /// // Parent directory does not exist. + /// } + /// } + /// + /// + public static void Create(string path, bool recursive = false) + { + Create(new QuickIOPathInfo(path), recursive); + } + + /// + /// Creates a new directory. If is false, the parent directory must exist. + /// + /// The directory. + /// If is false, the parent directory must exist. + /// if true not exception will be fired if directory already exists + /// http://msdn.microsoft.com/en-us/library/54a0at6s(v=vs.110).aspx + /// The specified path already exists. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// + /// Creates directory structure + /// + /// public static void Create_With_PathInfo_Example( ); + /// { + /// QuickIOPathInfo pathInfo = new QuickIOPathInfo( @"C:\temp\QuickIOTest\sub\folder\tree" ); + /// + /// // Creates directory C:\temp\QuickIOTest\sub\folder\tree and all not existing parent folders + /// QuickIODirectory.Create( pathInfo, recursive: true ); + /// } + /// + /// + /// + /// Shows how to handle sample exception if parent directory does not exist. + /// + /// public static void Create_With_StringPath_Example() + /// { + /// QuickIOPathInfo pathInfo = new QuickIOPathInfo( @"C:\temp\QuickIOTest\sub\folder\tree" ); + /// + /// try + /// { + /// QuickIODirectory.Create( pathInfo, recursive: false ); + /// } + /// catch ( PathNotFoundException pathNotFoundException ) + /// { + /// // Parent directory does not exist. + /// } + /// } + /// + /// + public static void Create(QuickIOPathInfo pathInfo, bool recursive = false) + { + InternalQuickIO.CreateDirectory(pathInfo, recursive); + } +} diff --git a/src/QuickIO/QuickIODirectory_Create_Async.cs b/src/QuickIO/QuickIODirectory_Create_Async.cs new file mode 100644 index 0000000..ace4148 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Create_Async.cs @@ -0,0 +1,32 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIODirectory +{ + /// + /// Creates a new directory. If is false, the parent directory must exist. + /// + /// The path to the directory. + /// If is false, the parent directory must exist. + /// http://msdn.microsoft.com/en-us/library/54a0at6s(v=vs.110).aspx + /// The specified path already exists. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + public static Task CreateAsync(string path, bool recursive = false) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Create(path, recursive)); + } + + /// + /// Creates a new directory. If is false, the parent directory must exist. + /// + /// The directory. + /// If is false, the parent directory must exist. + /// http://msdn.microsoft.com/en-us/library/54a0at6s(v=vs.110).aspx + /// The specified path already exists. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + public static Task CreateAsync(QuickIOPathInfo pathInfo, bool recursive = false) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Create(pathInfo, recursive)); + } +} diff --git a/src/QuickIO/QuickIODirectory_Delete.cs b/src/QuickIO/QuickIODirectory_Delete.cs new file mode 100644 index 0000000..5ff0be0 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Delete.cs @@ -0,0 +1,89 @@ +using SchwabenCode.QuickIO.Internal; + + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIODirectory +{ + /// + /// Deletes the specified directory and, if indicated, any subdirectories and files in the directory. + /// + /// The name of the directory to remove. + /// true to remove directories, subdirectories, and files in path; otherwise, false. + /// http://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// The directory is not empty. + /// + /// Creates directory structure + /// + /// public static void Create_With_StringPath_Example() + /// { + /// // Deletes directory C:\temp\QuickIOTest\sub\folder\tree and subfolders and files + /// QuickIODirectory.Delete( @"C:\temp\QuickIOTest\sub\folder\tree", recursive: true ); + /// } + /// + /// + /// + /// Shows how to handle sample exception if directory is not empty + /// + /// public static void Create_With_StringPath_Example() + /// { + /// try + /// { + /// QuickIODirectory.Delete( @"C:\temp\QuickIOTest\sub\folder\tree", recursive: false ); + /// } + /// catch ( DirectoryNotEmptyException directoryNotEmptyException ) + /// { + /// // Directoy is not empty + /// } + /// } + /// + /// + public static void Delete(string path, bool recursive = false) + { + Delete(new QuickIOPathInfo(path), recursive); + } + + /// + /// Deletes the specified directory and, if indicated, any subdirectories and files in the directory. + /// + /// The name of the directory to remove. + /// true to remove directories, subdirectories, and files in path; otherwise, false. + /// http://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// The directory is not empty. + /// + /// Creates directory structure + /// + /// public static void Create_With_StringPath_Example() + /// { + /// QuickIOPathInfo pathInfo = new QuickIOPathInfo( @"C:\temp\QuickIOTest\sub\folder\tree" ); + /// + /// // Deletes directory C:\temp\QuickIOTest\sub\folder\tree and subfolders and files + /// QuickIODirectory.Delete( pathInfo, recursive: true ); + /// } + /// + /// + /// + /// Shows how to handle sample exception if directory is not empty + /// + /// public static void Create_With_StringPath_Example() + /// { + /// QuickIOPathInfo pathInfo = new QuickIOPathInfo( @"C:\temp\QuickIOTest\sub\folder\tree" ); + /// + /// try + /// { + /// QuickIODirectory.Delete( pathInfo, recursive: false ); + /// } + /// catch ( DirectoryNotEmptyException directoryNotEmptyException ) + /// { + /// // Directoy is not empty + /// } + /// } + /// + /// + public static void Delete(QuickIOPathInfo info, bool recursive = false) + { + InternalQuickIO.DeleteDirectory(info, recursive); + } +} diff --git a/src/QuickIO/QuickIODirectory_Delete_Async.cs b/src/QuickIO/QuickIODirectory_Delete_Async.cs new file mode 100644 index 0000000..bc07acc --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Delete_Async.cs @@ -0,0 +1,33 @@ +using SchwabenCode.QuickIO.Compatibility; + + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIODirectory +{ + /// + /// Deletes the specified directory and, if indicated, any subdirectories and files in the directory. + /// + /// The name of the directory to remove. + /// true to remove directories, subdirectories, and files in path; otherwise, false. + /// http://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// The directory is not empty. + public static Task DeleteAsync(string path, bool recursive = false) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Delete(path, recursive)); + } + + /// + /// Deletes the specified directory and, if indicated, any subdirectories and files in the directory. + /// + /// The name of the directory to remove. + /// true to remove directories, subdirectories, and files in path; otherwise, false. + /// http://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// The directory is not empty. + public static Task DeleteAsync(QuickIOPathInfo info, bool recursive = false) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Delete(info, recursive)); + } +} diff --git a/src/QuickIO/QuickIODirectory_Enumerations.cs b/src/QuickIO/QuickIODirectory_Enumerations.cs new file mode 100644 index 0000000..2f179f9 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Enumerations.cs @@ -0,0 +1,319 @@ +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIODirectory +{ + #region EnumerateDirectoryPaths + + /// + /// Returns an enumerable collection of directory names in a specified path. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + /// http://msdn.microsoft.com/en-us/library/dd383304(v=vs.110).aspx + public static IEnumerable EnumerateDirectoryPaths(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return EnumerateDirectoryPaths(new QuickIOPathInfo(path), pattern, searchOption, pathFormatReturn, enumerateOptions); + } + + /// + /// Returns an enumerable collection of directory names in a specified path. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + /// http://msdn.microsoft.com/en-us/library/dd383304(v=vs.110).aspx + public static IEnumerable EnumerateDirectoryPaths(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return EnumerateDirectoryPaths(directoryInfo.PathInfo, pattern, searchOption, pathFormatReturn, enumerateOptions); + } + + /// + /// Returns an enumerable collection of directory names in a specified path. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + /// http://msdn.microsoft.com/en-us/library/dd383304(v=vs.110).aspx + public static IEnumerable EnumerateDirectoryPaths(QuickIOPathInfo info, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateDirectoryPaths(info.FullNameUnc, pattern, searchOption, enumerateOptions, pathFormatReturn); + } + #endregion + + #region EnumerateDirectories + /// + /// Returns an enumerable collection of directories in a specified path. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + /// http://msdn.microsoft.com/en-us/library/dd383304(v=vs.110).aspx + /// + /// + /// // Get subfolders + /// IEnumerable>QuickIODirectoryInfo< allSubFolders = QuickIODirectory.EnumerateDirectories( @"C:\temp\QuickIO", SearchOption.AllDirectories ); + /// + /// foreach ( QuickIODirectoryInfo directoryInfo in allSubFolders ) + /// { + /// Console.WriteLine( "Directory found: {0} Readonly: {1}", directoryInfo.FullName, directoryInfo.IsReadOnly ); + /// } + /// + /// + public static IEnumerable EnumerateDirectories(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return EnumerateDirectories(new QuickIOPathInfo(path), pattern, searchOption, enumerateOptions); + } + + /// + /// Returns an enumerable collection of directories in a specified path. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + /// http://msdn.microsoft.com/en-us/library/dd383304(v=vs.110).aspx + public static IEnumerable EnumerateDirectories(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return EnumerateDirectories(directoryInfo.PathInfo, pattern, searchOption, enumerateOptions); + } + + /// + /// Returns an enumerable collection of directories names in a specified path. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + /// http://msdn.microsoft.com/en-us/library/dd383304(v=vs.110).aspx + public static IEnumerable EnumerateDirectories(QuickIOPathInfo info, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateDirectories(info, pattern, searchOption, enumerateOptions); + } + #endregion + + #region EnumerateFilePaths + /// + /// Returns an enumerable collection of file names in a specified path. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + /// http://msdn.microsoft.com/en-us/library/dd383458(v=vs.110).aspx + public static IEnumerable EnumerateFilePaths(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return EnumerateFilePaths(new QuickIOPathInfo(path), pattern, searchOption, pathFormatReturn, enumerateOptions); + } + + /// + /// Returns an enumerable collection of file names in a specified path. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + /// http://msdn.microsoft.com/en-us/library/dd383458(v=vs.110).aspx + public static IEnumerable EnumerateFilePaths(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return EnumerateFilePaths(directoryInfo.PathInfo, pattern, searchOption, pathFormatReturn, enumerateOptions); + } + + /// + /// Returns an enumerable collection of file names in a specified path. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + /// http://msdn.microsoft.com/en-us/library/dd383458(v=vs.110).aspx + public static IEnumerable EnumerateFilePaths(QuickIOPathInfo info, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateFilePaths(info.FullNameUnc, pattern, searchOption, enumerateOptions, pathFormatReturn); + } + #endregion + + #region EnumerateFiles + + /// + /// Returns an enumerable collection of files in a specified path. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + /// http://msdn.microsoft.com/en-us/library/dd383458(v=vs.110).aspx + /// + /// + /// // Get subfiles + /// IEnumerable<QuickIOFileInfo> allSubFiles = QuickIODirectory.EnumerateFiles( @"C:\temp\QuickIO", SearchOption.AllDirectories ); + /// + /// foreach ( QuickIOFileInfo fileInfo in allSubFiles ) + /// { + /// Console.WriteLine( "File found: {0} Readonly: {1}", fileInfo.FullName, fileInfo.IsReadOnly ); + /// } + /// + /// + public static IEnumerable EnumerateFiles(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateFiles(new QuickIOPathInfo(path), pattern, searchOption, enumerateOptions); + } + + + /// + /// Returns an enumerable collection of files in a specified path. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + /// http://msdn.microsoft.com/en-us/library/dd383458(v=vs.110).aspx + public static IEnumerable EnumerateFiles(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateFiles(directoryInfo.PathInfo, pattern, searchOption, enumerateOptions); + } + + /// + /// Returns an enumerable collection of files in a specified path. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + public static IEnumerable EnumerateFiles(QuickIOPathInfo info, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateFiles(info, pattern, searchOption, enumerateOptions); + } + + #endregion + + #region EnumerateFileSystemEntryPaths + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// http://msdn.microsoft.com/en-us/library/dd383459(v=vs.110).aspx + public static IEnumerable> EnumerateFileSystemEntryPaths(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateFileSystemEntryPaths(new QuickIOPathInfo(path), pattern, searchOption, enumerateOptions, pathFormatReturn); + } + + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// http://msdn.microsoft.com/en-us/library/dd383459(v=vs.110).aspx + public static IEnumerable> EnumerateFileSystemEntryPaths(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateFileSystemEntryPaths(directoryInfo.PathInfo, pattern, searchOption, enumerateOptions, pathFormatReturn); + } + + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// http://msdn.microsoft.com/en-us/library/dd383459(v=vs.110).aspx + public static IEnumerable> EnumerateFileSystemEntryPaths(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateFileSystemEntryPaths(pathInfo, pattern, searchOption, enumerateOptions, pathFormatReturn); + } + + #endregion + + #region EnumerateFileSystemEntries + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// Options + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// http://msdn.microsoft.com/en-us/library/dd383459(v=vs.110).aspx + /// + /// + /// // Get all with one call + /// IEnumerable<KeyValuePair<QuickIOPathInfo, QuickIOFileSystemEntryType>gt; allSubEntries = QuickIODirectory.EnumerateFileSystemEntries( @"C:\temp\QuickIO", SearchOption.AllDirectories ); + /// foreach ( KeyValuePair<QuickIOPathInfo, QuickIOFileSystemEntryTypegt; subEntry in allSubEntries ) + /// { + /// var pathInfo = subEntry.Key; + /// var type = subEntry.Value; + /// + /// Console.WriteLine( "Entry found: {0} Readonly: {1}", pathInfo.FullName, type ); + /// } + /// + /// + public static IEnumerable> EnumerateFileSystemEntries(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateFileSystemEntries(new QuickIOPathInfo(path), pattern, searchOption, enumerateOptions); + } + + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// Options + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// http://msdn.microsoft.com/en-us/library/dd383459(v=vs.110).aspx + public static IEnumerable> EnumerateFileSystemEntries(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateFileSystemEntries(pathInfo, pattern, searchOption, enumerateOptions); + } + + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// Options + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// http://msdn.microsoft.com/en-us/library/dd383459(v=vs.110).aspx + public static IEnumerable> EnumerateFileSystemEntries(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateFileSystemEntries(directoryInfo.PathInfo, pattern, searchOption, enumerateOptions); + } + + #endregion +} diff --git a/src/QuickIO/QuickIODirectory_Enumerations_Async.cs b/src/QuickIO/QuickIODirectory_Enumerations_Async.cs new file mode 100644 index 0000000..7fd93e7 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Enumerations_Async.cs @@ -0,0 +1,284 @@ +using SchwabenCode.QuickIO.Compatibility; +using SchwabenCode.QuickIO.Internal; + + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIODirectory +{ + #region EnumerateDirectoryPaths + + /// + /// Returns an enumerable collection of directory names in a specified path in async context. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// Specifies the type of path to return. + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + public static Task> EnumerateDirectoryPathsAsync(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectoryPaths(new QuickIOPathInfo(path), pattern, searchOption, pathFormatReturn, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of directory names in a specified path in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + public static Task> EnumerateDirectoryPathsAsync(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectoryPaths(directoryInfo.PathInfo, pattern, searchOption, pathFormatReturn, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of directory names in a specified path in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// Specifies the type of path to return. + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + public static Task> EnumerateDirectoryPathsAsync(QuickIOPathInfo info, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectoryPaths(info, pattern, searchOption, pathFormatReturn, enumerateOptions)); + } + #endregion + + #region EnumerateDirectories + + /// + /// Returns an enumerable collection of directories in a specified path in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// Options + /// + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task> EnumerateDirectoriesAsync(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectories(new QuickIOPathInfo(path), pattern, searchOption, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of directories in a specified path in a seperate task created by the default in async context. + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task> EnumerateDirectoriesAsync(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectories(directoryInfo.PathInfo, pattern, searchOption, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of directories names in a specified path in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task> EnumerateDirectoriesAsync(QuickIOPathInfo info, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectories(info, pattern, searchOption, enumerateOptions)); + } + #endregion + + #region EnumerateFilePaths + + /// + /// Returns an enumerable collection of file names in a specified path in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task> EnumerateFilePathsAsync(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFilePaths(new QuickIOPathInfo(path), pattern, searchOption, pathFormatReturn, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of file names in a specified path in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task> EnumerateFilePathsAsync(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFilePaths(directoryInfo.PathInfo, pattern, searchOption, pathFormatReturn, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of file names in a specified path in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task> EnumerateFilePathsAsync(QuickIOPathInfo info, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => InternalQuickIO.EnumerateFilePaths(info.FullNameUnc, pattern, searchOption, enumerateOptions, pathFormatReturn)); + } + #endregion + + #region EnumerateFiles + + /// + /// Returns an enumerable collection of files in a specified path in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task> EnumerateFilesAsync(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFiles(new QuickIOPathInfo(path), pattern, searchOption, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of files in a specified path in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. # + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task> EnumerateFilesAsync(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFiles(directoryInfo.PathInfo, pattern, searchOption, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of files in a specified path in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// + /// Options + /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
/// + public static Task> EnumerateFilesAsync(QuickIOPathInfo info, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFiles(info, pattern, searchOption, enumerateOptions)); + } + #endregion + + #region EnumerateFileSystemEntryPaths + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task>> EnumerateFileSystemEntryPathsAsync(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFileSystemEntryPaths(new QuickIOPathInfo(path), pattern, searchOption, pathFormatReturn, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task>> EnumerateFileSystemEntryPathsAsync(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFileSystemEntryPaths(directoryInfo.PathInfo, pattern, searchOption, pathFormatReturn, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// Specifies the type of path to return. + /// Options + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task>> EnumerateFileSystemEntryPathsAsync(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFileSystemEntryPaths(pathInfo, pattern, searchOption, pathFormatReturn, enumerateOptions)); + } + #endregion + + #region EnumerateFileSystemEntries + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// Options + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task>> EnumerateFileSystemEntriesAsync(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFileSystemEntries(new QuickIOPathInfo(path), pattern, searchOption, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// Options + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// http://msdn.microsoft.com/en-us/library/dd383459(v=vs.110).aspx + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task>> EnumerateFileSystemEntriesAsync(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFileSystemEntries(pathInfo, pattern, searchOption, enumerateOptions)); + } + + /// + /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories in a seperate task created by the default . + /// + /// The directory to search. + /// Search pattern. Uses Win32 native filtering. + /// Options + /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. + /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. + /// http://msdn.microsoft.com/en-us/library/dd383459(v=vs.110).aspx + /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
+ public static Task>> EnumerateFileSystemEntriesAsync(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFileSystemEntries(directoryInfo.PathInfo, pattern, searchOption, enumerateOptions)); + } + #endregion +} diff --git a/src/QuickIO/QuickIODirectory_Exists.cs b/src/QuickIO/QuickIODirectory_Exists.cs new file mode 100644 index 0000000..5340a35 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Exists.cs @@ -0,0 +1,73 @@ +using SchwabenCode.QuickIO.Internal; +namespace SchwabenCode.QuickIO; + +public static partial class QuickIODirectory +{ + #region Exist + /// + /// Checks whether the given directory exists. + /// + /// The path to test. + /// true if exists; otherwise, false. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx + /// Searched for file but found folder. + /// Path is invalid. + public static bool Exists(string path) + { + QuickIOParsePathResult result = QuickIOPath.ParsePath( path ); + + return InternalDirectoryExists(path, result.IsRoot); + } + + /// + /// Checks whether the given directory exists. + /// + /// The path to test. + /// true if exists; otherwise, false. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx + /// Searched for file but found folder. + /// Path is invalid. + public static bool Exists(QuickIOPathInfo pathInfo) + { + return InternalDirectoryExists(pathInfo.FullNameUnc, pathInfo.IsRoot); + } + + /// + /// Checks whether the given directory exists. + /// + /// The path to test. + /// true if exists; otherwise, false. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx + /// Searched for file but found folder. + /// Path is invalid. + public static bool Exists(QuickIODirectoryInfo directoryInfo) + { + return InternalDirectoryExists(directoryInfo.FullNameUnc, directoryInfo.IsRoot); + } + + #endregion + + #region Internal Directory + private static bool InternalDirectoryExists(string uncPath, bool isRoot) + { + uint attrs = InternalQuickIO.SafeGetAttributes( uncPath, out _ ); + + if (Equals(attrs, 0xffffffff)) + { + return false; + } + + if (isRoot) + { + return true; + } + + if (InternalHelpers.ContainsFileAttribute(FileAttributes.Directory, (FileAttributes)attrs)) + { + return true; + } + + throw new UnmatchedFileSystemEntryTypeException(QuickIOFileSystemEntryType.Directory, QuickIOFileSystemEntryType.File, uncPath); + } + #endregion +} diff --git a/src/QuickIO/QuickIODirectory_Exists_Async.cs b/src/QuickIO/QuickIODirectory_Exists_Async.cs new file mode 100644 index 0000000..7466995 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Exists_Async.cs @@ -0,0 +1,48 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIODirectory +{ + #region Exist + /// + /// Checks whether the given directory exists. + /// + /// The path to test. + /// true if exists; otherwise, false. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx + /// Searched for file but found folder. + /// Path is invalid. + public static Task ExistsAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => Exists(path)); + } + + /// + /// Checks whether the given directory exists. + /// + /// The path to test. + /// true if exists; otherwise, false. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx + /// Searched for file but found folder. + /// Path is invalid. + public static Task ExistsAsync(QuickIOPathInfo pathInfo) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => Exists(pathInfo)); + } + + /// + /// Checks whether the given directory exists. + /// + /// The path to test. + /// true if exists; otherwise, false. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx + /// Searched for file but found folder. + /// Path is invalid. + public static Task ExistsAsync(QuickIODirectoryInfo directoryInfo) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => Exists(directoryInfo)); + } + + #endregion +} diff --git a/src/QuickIO/QuickIODirectory_FileTime.cs b/src/QuickIO/QuickIODirectory_FileTime.cs new file mode 100644 index 0000000..0c56cae --- /dev/null +++ b/src/QuickIO/QuickIODirectory_FileTime.cs @@ -0,0 +1,460 @@ +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIODirectory +{ + /// + /// Returns the creation time of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTime(String path) + { + return GetCreationTimeUtc(path).ToLocalTime(); + } + /// + /// Returns the creation time of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTime(QuickIOPathInfo info) + { + return GetCreationTimeUtc(info).ToLocalTime(); + } + /// + /// Returns the creation time of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTime(QuickIODirectoryInfo info) + { + return GetCreationTimeUtc(info.PathInfo).ToLocalTime(); + } + + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTimeUtc(String path) + { + return GetCreationTimeUtc(new QuickIOPathInfo(path)); + } + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTimeUtc(QuickIOPathInfo info) + { + return info.FindData.GetCreationTimeUtc(); + } + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime? GetCreationTimeUtc(QuickIODirectoryInfo info) + { + return info.FindData?.GetCreationTimeUtc(); + } + + /// + /// Returns the time of last access of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTime(String path) + { + return GetLastAccessTimeUtc(path).ToLocalTime(); + } + /// + /// Returns the time of last access of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTime(QuickIOPathInfo info) + { + return GetLastAccessTimeUtc(info).ToLocalTime(); + } + /// + /// Returns the time of last access of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTime(QuickIODirectoryInfo info) + { + return GetLastAccessTimeUtc(info.PathInfo).ToLocalTime(); + } + + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTimeUtc(String path) + { + return GetLastAccessTimeUtc(new QuickIOPathInfo(path)); + } + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTimeUtc(QuickIOPathInfo info) + { + return info.FindData.GetLastAccessTimeUtc(); + } + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime? GetLastAccessTimeUtc(QuickIODirectoryInfo info) + { + return info.FindData?.GetLastAccessTimeUtc(); + } + + /// + /// Returns the time of the file or directory was last written + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTime(String path) + { + return GetLastWriteTimeUtc(path).ToLocalTime(); + } + /// + /// Returns the time of the file or directory was last written + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTime(QuickIOPathInfo info) + { + return GetLastWriteTimeUtc(info).ToLocalTime(); + } + /// + /// Returns the time of the file or directory was last written + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTime(QuickIODirectoryInfo info) + { + return GetLastWriteTimeUtc(info.PathInfo).ToLocalTime(); + } + + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTimeUtc(String path) + { + return GetLastWriteTimeUtc(new QuickIOPathInfo(path)); + } + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTimeUtc(QuickIOPathInfo info) + { + return info.FindData.GetLastWriteTimeUtc(); + } + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime? GetLastWriteTimeUtc(QuickIODirectoryInfo info) + { + return info.FindData?.GetLastWriteTimeUtc(); + } + + /// + /// Sets the time the file was created. + /// + /// Affected file or directory + /// The time that is to be used + /// The time that is to be used + /// The time that is to be used + public static void SetAllFileTimes(String path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) + { + SetAllFileTimesUtc(path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime()); + } + /// + /// Sets the time the file was created. + /// + /// Affected file or directory + /// The time that is to be used + /// The time that is to be used + /// The time that is to be used + public static void SetAllFileTimes(QuickIOPathInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) + { + SetAllFileTimesUtc(info, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime()); + } + /// + /// Sets the time the file was created. + /// + /// Affected file or directory + /// The time that is to be used + /// The time that is to be used + /// The time that is to be used + public static void SetAllFileTimes(QuickIODirectoryInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) + { + SetAllFileTimesUtc(info, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime()); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static void SetAllFileTimesUtc(String path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + InternalQuickIO.SetAllFileTimes(new QuickIOPathInfo(path), creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static void SetAllFileTimesUtc(QuickIOPathInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + InternalQuickIO.SetAllFileTimes(info, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static void SetAllFileTimesUtc(QuickIODirectoryInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + InternalQuickIO.SetAllFileTimes(info.PathInfo, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc); + } + + /// + /// Defines the time at which the file or directory was created + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetCreationTime(String path, DateTime creationTime) + { + SetCreationTimeUtc(path, creationTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was created + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetCreationTime(QuickIOPathInfo info, DateTime creationTime) + { + SetCreationTimeUtc(info, creationTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was created + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetCreationTime(QuickIODirectoryInfo info, DateTime creationTime) + { + SetCreationTimeUtc(info, creationTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static void SetCreationTimeUtc(String path, DateTime creationTimeUtc) + { + InternalQuickIO.SetCreationTimeUtc(new QuickIOPathInfo(path), creationTimeUtc); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static void SetCreationTimeUtc(QuickIOPathInfo info, DateTime creationTimeUtc) + { + InternalQuickIO.SetCreationTimeUtc(info, creationTimeUtc); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static void SetCreationTimeUtc(QuickIODirectoryInfo info, DateTime creationTimeUtc) + { + InternalQuickIO.SetCreationTimeUtc(info.PathInfo, creationTimeUtc); + } + + /// + /// Defines the time at which the file or directory was last accessed + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetLastAccessTime(String path, DateTime lastAccessTime) + { + SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was last accessed + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx + public static void SetLastAccessTime(QuickIOPathInfo info, DateTime lastAccessTime) + { + SetLastAccessTimeUtc(info, lastAccessTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was last accessed + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx + public static void SetLastAccessTime(QuickIODirectoryInfo info, DateTime lastAccessTime) + { + SetLastAccessTimeUtc(info, lastAccessTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc) + { + InternalQuickIO.SetLastAccessTimeUtc(new QuickIOPathInfo(path), lastAccessTimeUtc); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static void SetLastAccessTimeUtc(QuickIOPathInfo info, DateTime lastAccessTimeUtc) + { + InternalQuickIO.SetLastAccessTimeUtc(info, lastAccessTimeUtc); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static void SetLastAccessTimeUtc(QuickIODirectoryInfo info, DateTime lastAccessTimeUtc) + { + InternalQuickIO.SetLastAccessTimeUtc(info.PathInfo, lastAccessTimeUtc); + } + + /// + /// Defines the time at which the file or directory was last written + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetLastWriteTime(String path, DateTime lastWriteTime) + { + SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was last written + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx + public static void SetLastWriteTime(QuickIOPathInfo info, DateTime lastWriteTime) + { + SetLastWriteTimeUtc(info, lastWriteTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was last written + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx + public static void SetLastWriteTime(QuickIODirectoryInfo info, DateTime lastWriteTime) + { + SetLastWriteTimeUtc(info, lastWriteTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc) + { + InternalQuickIO.SetLastWriteTimeUtc(new QuickIOPathInfo(path), lastWriteTimeUtc); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static void SetLastWriteTimeUtc(QuickIOPathInfo info, DateTime lastWriteTimeUtc) + { + InternalQuickIO.SetLastWriteTimeUtc(info, lastWriteTimeUtc); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static void SetLastWriteTimeUtc(QuickIODirectoryInfo info, DateTime lastWriteTimeUtc) + { + InternalQuickIO.SetLastWriteTimeUtc(info.PathInfo, lastWriteTimeUtc); + } +} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.FileTime.tt b/src/QuickIO/QuickIODirectory_FileTime.tt similarity index 51% rename from src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.FileTime.tt rename to src/QuickIO/QuickIODirectory_FileTime.tt index 537f473..40932be 100644 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.FileTime.tt +++ b/src/QuickIO/QuickIODirectory_FileTime.tt @@ -1,6 +1,6 @@ <#@ template language="C#" hostspecific="true" #> -<#@ include file="..\Templates\SaveOutput.tt" #> -<#@ include file="..\Templates\StaticFileTimeMethods.tt" #> +<#@ include file=".\CodeTemplates\SaveOutput.tt" #> +<#@ include file=".\CodeTemplates\StaticFileTimeMethods.tt" #> <#@ output extension=".cs" #> <# Generate("QuickIODirectory"); diff --git a/src/QuickIO/QuickIODirectory_FileTime_Async.cs b/src/QuickIO/QuickIODirectory_FileTime_Async.cs new file mode 100644 index 0000000..550620c --- /dev/null +++ b/src/QuickIO/QuickIODirectory_FileTime_Async.cs @@ -0,0 +1,460 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIODirectory +{ + /// + /// Returns the creation time of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetCreationTime(path)); + } + /// + /// Returns the creation time of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetCreationTime(info)); + } + /// + /// Returns the creation time of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeAsync(QuickIODirectoryInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetCreationTime(info)); + } + + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeUtcAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetCreationTimeUtc(path)); + } + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeUtcAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetCreationTimeUtc(info)); + } + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeUtcAsync(QuickIODirectoryInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetCreationTimeUtc(info)); + } + + /// + /// Returns the time of last access of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetLastAccessTime(path)); + } + /// + /// Returns the time of last access of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetLastAccessTime(info)); + } + /// + /// Returns the time of last access of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeAsync(QuickIODirectoryInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetLastAccessTime(info)); + } + + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeUtcAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetLastAccessTimeUtc(path)); + } + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeUtcAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetLastAccessTimeUtc(info)); + } + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeUtcAsync(QuickIODirectoryInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetLastAccessTimeUtc(info)); + } + + /// + /// Returns the time of the file or directory was last written + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetLastAccessTimeUtc(path)); + } + /// + /// Returns the time of the file or directory was last written + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetLastAccessTimeUtc(info)); + } + /// + /// Returns the time of the file or directory was last written + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeAsync(QuickIODirectoryInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetLastAccessTimeUtc(info)); + } + + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeUtcAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetLastWriteTimeUtc(path)); + } + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeUtcAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetLastWriteTimeUtc(info)); + } + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeUtcAsync(QuickIODirectoryInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetLastWriteTimeUtc(info)); + } + + /// + /// Sets the time the file was created. + /// + /// Affected file or directory + /// The time that is to be used + /// The time that is to be used + /// The time that is to be used + public static Task SetAllFileTimesAsync(string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetAllFileTimes(path, creationTime, lastAccessTime, lastWriteTime)); + } + /// + /// Sets the time the file was created. + /// + /// Affected file or directory + /// The time that is to be used + /// The time that is to be used + /// The time that is to be used + public static Task SetAllFileTimesAsync(QuickIOPathInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetAllFileTimes(info, creationTime, lastAccessTime, lastWriteTime)); + } + /// + /// Sets the time the file was created. + /// + /// Affected file or directory + /// The time that is to be used + /// The time that is to be used + /// The time that is to be used + public static Task SetAllFileTimesAsync(QuickIODirectoryInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetAllFileTimes(info, creationTime, lastAccessTime, lastWriteTime)); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static Task SetAllFileTimesUtcAsync(string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetAllFileTimesUtc(path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc)); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static Task SetAllFileTimesUtcAsync(QuickIOPathInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetAllFileTimesUtc(info, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc)); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static Task SetAllFileTimesUtcAsync(QuickIODirectoryInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetAllFileTimesUtc(info, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc)); + } + + /// + /// Defines the time at which the file or directory was created + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetCreationTimeAsync(string path, DateTime creationTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetCreationTime(path, creationTime)); + } + /// + /// Defines the time at which the file or directory was created + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetCreationTimeAsync(QuickIOPathInfo info, DateTime creationTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetCreationTime(info, creationTime)); + } + /// + /// Defines the time at which the file or directory was created + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetCreationTimeAsync(QuickIODirectoryInfo info, DateTime creationTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetCreationTime(info, creationTime)); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static Task SetCreationTimeUtcAsync(string path, DateTime creationTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetCreationTimeUtc(path, creationTimeUtc)); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static Task SetCreationTimeUtcAsync(QuickIOPathInfo info, DateTime creationTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetCreationTimeUtc(info, creationTimeUtc)); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static Task SetCreationTimeUtcAsync(QuickIODirectoryInfo info, DateTime creationTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetCreationTimeUtc(info, creationTimeUtc)); + } + + /// + /// Defines the time at which the file or directory was last accessed + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetLastAccessTimeAsync(string path, DateTime lastAccessTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetLastAccessTime(path, lastAccessTime)); + } + /// + /// Defines the time at which the file or directory was last accessed + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx + public static Task SetLastAccessTimeAsync(QuickIOPathInfo info, DateTime lastAccessTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetLastAccessTime(info, lastAccessTime)); + } + /// + /// Defines the time at which the file or directory was last accessed + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx + public static Task SetLastAccessTimeAsync(QuickIODirectoryInfo info, DateTime lastAccessTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetLastAccessTime(info, lastAccessTime)); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static Task SetLastAccessTimeUtcAsync(string path, DateTime lastAccessTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetLastAccessTimeUtc(path, lastAccessTimeUtc)); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static Task SetLastAccessTimeUtcAsync(QuickIOPathInfo info, DateTime lastAccessTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetLastAccessTimeUtc(info, lastAccessTimeUtc)); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static Task SetLastAccessTimeUtcAsync(QuickIODirectoryInfo info, DateTime lastAccessTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetLastAccessTimeUtc(info, lastAccessTimeUtc)); + } + + /// + /// Defines the time at which the file or directory was last written + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetLastWriteTimeAsync(string path, DateTime lastWriteTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetLastWriteTime(path, lastWriteTime)); + } + /// + /// Defines the time at which the file or directory was last written + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx + public static Task SetLastWriteTimeAsync(QuickIOPathInfo info, DateTime lastWriteTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetLastWriteTime(info, lastWriteTime)); + } + /// + /// Defines the time at which the file or directory was last written + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx + public static Task SetLastWriteTimeAsync(QuickIODirectoryInfo info, DateTime lastWriteTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetLastWriteTime(info, lastWriteTime)); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static Task SetLastWriteTimeUtcAsync(string path, DateTime lastWriteTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetLastWriteTimeUtc(path, lastWriteTimeUtc)); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static Task SetLastWriteTimeUtcAsync(QuickIOPathInfo info, DateTime lastWriteTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetLastWriteTimeUtc(info, lastWriteTimeUtc)); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static Task SetLastWriteTimeUtcAsync(QuickIODirectoryInfo info, DateTime lastWriteTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIODirectory.SetLastWriteTimeUtc(info, lastWriteTimeUtc)); + } +} diff --git a/src/QuickIO/QuickIODirectory_FileTime_Async.tt b/src/QuickIO/QuickIODirectory_FileTime_Async.tt new file mode 100644 index 0000000..872bf00 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_FileTime_Async.tt @@ -0,0 +1,7 @@ +<#@ template language="C#" hostspecific="true" #> +<#@ include file=".\CodeTemplates\SaveOutput.tt" #> +<#@ include file=".\CodeTemplates\StaticFileTimeMethods_Async.tt" #> +<#@ output extension=".cs" #> +<# + Generate("QuickIODirectory"); +#> \ No newline at end of file diff --git a/src/QuickIO/QuickIODirectory_Metadata.cs b/src/QuickIO/QuickIODirectory_Metadata.cs new file mode 100644 index 0000000..ec70756 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Metadata.cs @@ -0,0 +1,38 @@ +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIODirectory +{ + /// + /// Receives of current directory + /// + /// + public static QuickIODirectoryMetadata? GetMetadata(string directoryPath, + QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + Invariant.NotEmpty(directoryPath); + return InternalQuickIO.EnumerateDirectoryMetadata(new QuickIOPathInfo(directoryPath), enumerateOptions); + } + + /// + /// Receives of current directory + /// + /// + public static QuickIODirectoryMetadata? GetMetadata(QuickIODirectoryInfo directoryInfo, + QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateDirectoryMetadata(directoryInfo.PathInfo, enumerateOptions); + } + + /// + /// Receives of current directory + /// + /// + public static QuickIODirectoryMetadata? GetMetadata(QuickIOPathInfo pathInfo, + QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return InternalQuickIO.EnumerateDirectoryMetadata(pathInfo, enumerateOptions); + } + +} diff --git a/src/QuickIO/QuickIODirectory_Metadata_Async.cs b/src/QuickIO/QuickIODirectory_Metadata_Async.cs new file mode 100644 index 0000000..73044bd --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Metadata_Async.cs @@ -0,0 +1,33 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIODirectory +{ + /// + /// Receives of current directory using a sperare Task + /// + /// + public static Task GetMetadataAsync(string directoryPath, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetMetadata(directoryPath, enumerateOptions)); + } + + /// + /// Receives of current directory using a sperare Task + /// + /// + public static Task GetMetadataAsync(QuickIODirectoryInfo directoryInfo, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetMetadata(directoryInfo, enumerateOptions)); + } + + /// + /// Receives of current directory using a sperare Task + /// + /// + public static Task GetMetadataAsync(QuickIOPathInfo pathInfo, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetMetadata(pathInfo, enumerateOptions)); + } +} diff --git a/src/QuickIO/QuickIODirectory_Move.cs b/src/QuickIO/QuickIODirectory_Move.cs new file mode 100644 index 0000000..d711d80 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Move.cs @@ -0,0 +1,32 @@ +using System.Runtime.InteropServices; +using SchwabenCode.QuickIO.Internal; +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIODirectory +{ + /// + /// Moves a directory + /// + /// Fullname to move + /// Full targetname + /// true to overwrite target + /// Target exists + public static void Move(string from, string to, bool overwrite = false) + { + Invariant.NotEmpty(from); + Invariant.NotEmpty(to); + + if (!overwrite && Exists(to)) + { + throw new DirectoryAlreadyExistsException("Target directory already exists.", to); + } + + if (!Win32SafeNativeMethods.MoveFile(from, to)) + { + int win32Error = Marshal.GetLastWin32Error( ); + InternalQuickIOCommon.NativeExceptionMapping(from, win32Error); + } + } +} diff --git a/src/QuickIO/QuickIODirectory_Move_Async.cs b/src/QuickIO/QuickIODirectory_Move_Async.cs new file mode 100644 index 0000000..7bd7c69 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Move_Async.cs @@ -0,0 +1,18 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIODirectory +{ + /// + /// Moves a directory + /// + /// Fullname to move + /// Full targetname + /// true to overwrite target + /// Target exists + public static Task MoveAsync(string from, string to, bool overwrite = false) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Move(from, to, overwrite)); + } +} diff --git a/src/QuickIO/QuickIODirectory_Root.cs b/src/QuickIO/QuickIODirectory_Root.cs new file mode 100644 index 0000000..8fbdedf --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Root.cs @@ -0,0 +1,38 @@ + +namespace SchwabenCode.QuickIO; + +public partial class QuickIODirectory +{ + /// + /// Returns the root information + /// + /// The path of a file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static QuickIOPathInfo? GetDirectoryRoot(string path) + { + return GetDirectoryRoot(new QuickIOPathInfo(path)); + } + + /// + /// Returns the root information + /// + /// A file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static QuickIOPathInfo? GetDirectoryRoot(QuickIOPathInfo info) + { + return info.Root; + } + + /// + /// Returns the root information + /// + /// A file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static QuickIOPathInfo? GetDirectoryRoot(QuickIODirectoryInfo info) + { + return info.Root; + } +} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.Attributes.tt b/src/QuickIO/QuickIODirectory_Root.tt similarity index 52% rename from src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.Attributes.tt rename to src/QuickIO/QuickIODirectory_Root.tt index f86d137..8a6cf42 100644 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.Attributes.tt +++ b/src/QuickIO/QuickIODirectory_Root.tt @@ -1,6 +1,6 @@ <#@ template language="C#" hostspecific="true" #> -<#@ include file="..\Templates\SaveOutput.tt" #> -<#@ include file="..\Templates\StaticAttributeMethods.tt" #> +<#@ include file=".\CodeTemplates\SaveOutput.tt" #> +<#@ include file=".\CodeTemplates\StaticRootMethods.tt" #> <#@ output extension=".cs" #> <# Generate("QuickIODirectory"); diff --git a/src/QuickIO/QuickIODirectory_Root_Async.cs b/src/QuickIO/QuickIODirectory_Root_Async.cs new file mode 100644 index 0000000..dc78900 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Root_Async.cs @@ -0,0 +1,39 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIODirectory +{ + /// + /// Returns the root information + /// + /// The path of a file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static Task GetDirectoryRootAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetDirectoryRoot(path)); + } + + /// + /// Returns the root information + /// + /// A file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static Task GetDirectoryRootAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetDirectoryRoot(info)); + } + + /// + /// Returns the root information + /// + /// A file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static Task GetDirectoryRootAsync(QuickIODirectoryInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIODirectory.GetDirectoryRoot(info)); + } +} diff --git a/src/QuickIO/QuickIODirectory_Root_Async.tt b/src/QuickIO/QuickIODirectory_Root_Async.tt new file mode 100644 index 0000000..dea8cb8 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Root_Async.tt @@ -0,0 +1,7 @@ +<#@ template language="C#" hostspecific="true" #> +<#@ include file=".\CodeTemplates\SaveOutput.tt" #> +<#@ include file=".\CodeTemplates\StaticRootMethods_Async.tt" #> +<#@ output extension=".cs" #> +<# + Generate("QuickIODirectory"); +#> \ No newline at end of file diff --git a/src/QuickIO/QuickIODirectory_Statistics.cs b/src/QuickIO/QuickIODirectory_Statistics.cs new file mode 100644 index 0000000..5064ff4 --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Statistics.cs @@ -0,0 +1,93 @@ +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +/// +/// Provides static methods to access folders. For example creating, deleting and retrieving content and security information such as the owner. +/// +public static partial class QuickIODirectory +{ + /// + /// Gets the directory statistics: total files, folders and bytes + /// + /// + /// A object that holds the folder statistics such as number of folders, files and total bytes + /// + /// This example shows how to call + /// GetStatistics + /// + /// and write the result to the console. + /// + /// public static void GetStatistics_With_StringPath_Example() + /// { + /// const string targetDirectoryPath = @"C:\temp\QuickIOTest"; + /// + /// // Get statistics + /// QuickIOFolderStatisticResult statsResult = QuickIODirectory.GetStatistics( targetDirectoryPath ); + /// + /// // Output + /// Console.WriteLine( "[Stats] Folders: '{0}' Files: '{1}' Total TotalBytes '{2}'", statsResult.FolderCount, statsResult.FileCount, statsResult.TotalBytes ); + /// } + /// + /// + public static QuickIOFolderStatisticResult? GetStatistics(string path) + { + return GetStatistics(new QuickIOPathInfo(path)); + } + + /// + /// Gets the directory statistics: total files, folders and bytes + /// + /// + /// A object that holds the folder statistics such as number of folders, files and total bytes + /// + /// This example shows how to call + /// GetStatistics + /// + /// with and write the result to the console. + /// + ///public static void GetStatistics_With_PathInfo_Example() + ///{ + /// QuickIOPathInfo targetDirectoryPathInfo = new QuickIOPathInfo( @"C:\temp\QuickIOTest" ); + /// + /// // Get statistics + /// QuickIOFolderStatisticResult stats = QuickIODirectory.GetStatistics( targetDirectoryPathInfo ); + /// + /// // Output + /// Console.WriteLine( "[Stats] Folders: '{0}' Files: '{1}' Total TotalBytes '{2}'", stats.FolderCount, stats.FileCount, stats.TotalBytes ); + ///} + /// + /// + public static QuickIOFolderStatisticResult? GetStatistics(QuickIOPathInfo pathInfo) + { + return InternalQuickIO.GetDirectoryStatistics(pathInfo); + } + + /// + /// Gets the directory statistics: total files, folders and bytes + /// + /// + /// A object that holds the folder statistics such as number of folders, files and total bytes + /// + /// This example shows how to call + /// GetStatistics + /// + /// with and write the result to the console. + /// + ///public static void GetStatistics_With_DirectoryInfo_Example() + ///{ + /// QuickIODirectoryInfo targetDirectoryPathInfo = new QuickIODirectoryInfo( @"C:\temp\QuickIOTest" ); + /// + /// // Get statistics + /// QuickIOFolderStatisticResult stats = QuickIODirectory.GetStatistics( targetDirectoryPathInfo ); + /// + /// // Output + /// Console.WriteLine( "[Stats] Folders: '{0}' Files: '{1}' Total TotalBytes '{2}'", stats.FolderCount, stats.FileCount, stats.TotalBytes ); + ///} + /// + /// + public static QuickIOFolderStatisticResult? GetStatistics(QuickIODirectoryInfo directoryInfo) + { + return InternalQuickIO.GetDirectoryStatistics(directoryInfo.PathInfo); + } +} diff --git a/src/QuickIO/QuickIODirectory_Statistics_Async.cs b/src/QuickIO/QuickIODirectory_Statistics_Async.cs new file mode 100644 index 0000000..8666dca --- /dev/null +++ b/src/QuickIO/QuickIODirectory_Statistics_Async.cs @@ -0,0 +1,39 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +/// +/// Provides static methods to access folders. For example creating, deleting and retrieving content and security information such as the owner. +/// +public static partial class QuickIODirectory +{ + /// + /// Gets the directory statistics: total files, folders and bytes + /// + /// + /// A object that holds the folder statistics such as number of folders, files and total bytes + public static Task GetStatisticsAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetStatistics(path)); + } + + /// + /// Gets the directory statistics: total files, folders and bytes + /// + /// + /// A object that holds the folder statistics such as number of folders, files and total bytes + public static Task GetStatisticsAsync(QuickIOPathInfo pathInfo) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetStatistics(pathInfo)); + } + + /// + /// Gets the directory statistics: total files, folders and bytes + /// + /// + /// A object that holds the folder statistics such as number of folders, files and total bytes + public static Task GetStatisticsAsync(QuickIODirectoryInfo directoryInfo) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetStatistics(directoryInfo)); + } +} diff --git a/src/QuickIO/QuickIODiskInformation.cs b/src/QuickIO/QuickIODiskInformation.cs new file mode 100644 index 0000000..8c38eee --- /dev/null +++ b/src/QuickIO/QuickIODiskInformation.cs @@ -0,0 +1,29 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Disk metadata information +/// +public sealed partial class QuickIODiskInformation +{ + internal QuickIODiskInformation(ulong freeBytes, ulong totalBytes, ulong totalFreeBytes) + { + FreeBytes = freeBytes; + TotalBytes = totalBytes; + TotalFreeBytes = totalFreeBytes; + } + + /// + /// Total available number of bytes for the user who executed the API call. + /// + public ulong FreeBytes { get; private set; } + + /// + /// Total bytes of share + /// + public ulong TotalBytes { get; private set; } + + /// + /// Total free bytes for all users + /// + public ulong TotalFreeBytes { get; private set; } +} diff --git a/src/QuickIO/QuickIOEnumerateOptions.cs b/src/QuickIO/QuickIOEnumerateOptions.cs new file mode 100644 index 0000000..aa01e6b --- /dev/null +++ b/src/QuickIO/QuickIOEnumerateOptions.cs @@ -0,0 +1,18 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Options for enumerations +/// +[Flags] +public enum QuickIOEnumerateOptions +{ + /// + /// No options + /// + None, + /// + /// Suppresses all exceptions + /// + SuppressAllExceptions + +} diff --git a/src/QuickIO/QuickIOExtensions.cs b/src/QuickIO/QuickIOExtensions.cs new file mode 100644 index 0000000..96bb779 --- /dev/null +++ b/src/QuickIO/QuickIOExtensions.cs @@ -0,0 +1,50 @@ + +namespace SchwabenCode.QuickIO; + +/// +/// Provides Extensions +/// +public static class QuickIOExtensions +{ + + /// + /// Returns a of the current path + /// + /// + /// + public static QuickIOFileInfo ToQuickIO(this FileInfo source) + { + return (QuickIOFileInfo)source; + } + + /// + /// Returns a of the current path + /// + /// + /// + public static QuickIODirectoryInfo ToQuickIO(this DirectoryInfo source) + { + return (QuickIODirectoryInfo)source; + } + + + /// + /// Returns a of the current path + /// + /// + /// + public static FileInfo AsFileInfo(this QuickIOFileInfo source) + { + return new FileInfo(source.FullName); + } + + /// + /// Returns a of the current path + /// + /// + /// + public static DirectoryInfo AsDirectoryInfo(this QuickIODirectoryInfo source) + { + return new DirectoryInfo(source.FullName); + } +} diff --git a/src/QuickIO/QuickIOFile.cs b/src/QuickIO/QuickIOFile.cs new file mode 100644 index 0000000..f6835e0 --- /dev/null +++ b/src/QuickIO/QuickIOFile.cs @@ -0,0 +1,333 @@ +using SchwabenCode.QuickIO.Compatibility; +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +/// +/// Provides static methods to access files. For example creating, deleting and retrieving content and security information such as the owner. +/// +public static partial class QuickIOFile +{ + + /// + /// Copies an existing file. Overwrites an existing file if is true + /// + /// The file to copy. + /// Target directory + /// New File name. Null or empty to use 's name + /// true to overwrite existing file + /// http://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx + /// Filesystem is busy + public static void CopyToDirectory(string sourceFileName, string targetDirectory, + string? newFileName = null, bool overwrite = false) + { + CopyToDirectory(InternalQuickIO.LoadFileFromPathInfo(new QuickIOPathInfo(sourceFileName)), InternalQuickIO.LoadDirectoryFromPathInfo(new QuickIOPathInfo(targetDirectory)), newFileName, overwrite); + } + + /// + /// Copies an existing file. Overwrites an existing file if is true + /// + /// The file to copy. + /// Target directory + /// New File name. Null or empty to use 's name + /// true to overwrite existing file + /// http://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx + /// Filesystem is busy + public static Task CopyToDirectoryAsync(string sourceFileName, string targetDirectory, + string? newFileName = null, bool overwrite = false) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => CopyToDirectory(sourceFileName, targetDirectory, newFileName, overwrite)); + } + + /// + /// Copies an existing file. Overwrites an existing file if is true + /// + /// The file to copy. + /// Target directory + /// New File name. Null or empty to use ' name + /// true to overwrite existing files + /// http://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx + /// Filesystem is busy + public static void CopyToDirectory(QuickIOFileInfo sourceFileName, QuickIODirectoryInfo targetDirectory, + string? newFileName = null, bool overwrite = false) + { + string targetFileName = sourceFileName.Name; + if (!string.IsNullOrEmpty(newFileName)) + { + // TODO: Check for invalid chars + targetFileName = newFileName; + } + + Copy(sourceFileName.FullNameUnc, QuickIOPath.Combine(targetDirectory.FullNameUnc, targetFileName), overwrite); + } + + /// + /// Copies an existing file. Overwrites an existing file if is true + /// + /// The file to copy. + /// Target directory + /// New File name. Null or empty to use ' name + /// true to overwrite existing files + /// http://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx + /// Filesystem is busy + public static Task CopyToDirectoryAsync(QuickIOFileInfo sourceFileName, QuickIODirectoryInfo targetDirectory, + string? newFileName = null, bool overwrite = false) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync( + () => CopyToDirectory(sourceFileName, targetDirectory, newFileName, overwrite)); + } + + /// + /// Copies an existing file. Overwrites an existing file if is true + /// + /// The file to copy. + /// Target file + /// true to overwrite existing files + /// Creates parent path if not exists. Decreases copy performance + /// http://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx + /// Filesystem is busy + public static void Copy(string uncSourceFullName, string uncTargetFullName, bool overwrite = false, bool createRecursive = true) + { + Invariant.NotEmpty(uncSourceFullName); + Invariant.NotEmpty(uncTargetFullName); + + if (createRecursive) + { + string? targetDirectoryPath = QuickIOPath.GetParentPath( uncTargetFullName ) + ?? throw new InvalidPathException("Invalid parent path. Cannot create directory."); + + try + { + QuickIODirectory.Create(targetDirectoryPath, true); + } + catch (PathAlreadyExistsException) + { + // yay ignore this! + } + } + + if (!InternalQuickIO.CopyFile(uncSourceFullName, uncTargetFullName, out int win32Error, overwrite)) + { + InternalQuickIOCommon.NativeExceptionMapping(!Exists(uncSourceFullName) ? uncSourceFullName : uncTargetFullName, win32Error); + } + } + + /// + /// Copies an existing file. Overwrites an existing file if is true + /// + /// The file to copy. + /// Target file + /// true to overwrite existing files + /// http://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx + /// Filesystem is busy + public static Task CopyAsync(string uncSourceFullName, string uncTargetFullName, bool overwrite = false) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Copy(uncSourceFullName, uncTargetFullName, overwrite)); + } + + + /// + /// Deletes the file. + /// + /// The fullname of the file to be deleted. + /// http://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx + /// File does not exist. + public static void Delete(string path) + { + Delete(new QuickIOPathInfo(path)); + } + /// + /// Deletes the file. + /// + /// The fullname of the file to be deleted. + /// http://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx + /// File does not exist. + public static Task DeleteAsync(string path) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Delete(path)); + } + + /// + /// Deletes the file. + /// + /// The file to be deleted. + /// http://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx + /// File does not exist. + public static void Delete(QuickIOPathInfo pathInfo) + { + InternalQuickIO.DeleteFile(pathInfo); + } + /// + /// Deletes the file. + /// + /// The file to be deleted. + /// http://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx + /// File does not exist. + public static Task DeleteAsync(QuickIOPathInfo pathInfo) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Delete(pathInfo)); + } + + /// + /// Checks whether the specified file exists. + /// + /// The path to check. + /// true if the caller has the required permissions and path contains the name of an existing file; otherwise, false + /// The original Exists method returns also false on null! http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx + /// Searched for file but found folder. + /// Path is invalid. + public static bool Exists(string path) + { + return InternalFileExists(QuickIOPath.ToUncPath(path)); + } + + /// + /// Checks whether the specified file exists. + /// + /// The path to check. + /// true if the caller has the required permissions and path contains the name of an existing file; otherwise, false + /// The original Exists method returns also false on null! http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx + /// Searched for file but found folder. + /// Path is invalid. + public static Task ExistsAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => Exists(path)); + } + + /// + /// Checks whether the specified file exists. + /// + /// The the file to check. + /// true if the caller has the required permissions and path contains the name of an existing file; otherwise, false + /// The original Exists method returns also false on null! http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx + /// Searched for file but found folder. + /// Path is invalid. + public static bool Exists(QuickIOPathInfo pathInfo) + { + return InternalFileExists(pathInfo.FullNameUnc); + } + + /// + /// Checks whether the specified file exists. + /// + /// The the file to check. + /// true if the caller has the required permissions and path contains the name of an existing file; otherwise, false + /// The original Exists method returns also false on null! http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx + /// Searched for file but found folder. + /// Path is invalid. + public static Task ExistsAsync(QuickIOPathInfo pathInfo) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => Exists(pathInfo)); + } + + /// + /// Checks whether the specified file exists. + /// + /// The the file to check. + /// true if the caller has the required permissions and path contains the name of an existing file; otherwise, false + /// The original Exists method returns also false on null! http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx + /// Searched for file but found folder. + /// Path is invalid. + public static bool Exists(QuickIOFileInfo fileInfo) + { + return InternalFileExists(fileInfo.FullNameUnc); + } + + /// + /// Checks whether the specified file exists. + /// + /// The the file to check. + /// true if the caller has the required permissions and path contains the name of an existing file; otherwise, false + /// The original Exists method returns also false on null! http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx + /// Searched for file but found folder. + /// Path is invalid. + public static Task ExistsAsync(QuickIOFileInfo fileInfo) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => Exists(fileInfo)); + } + + /// + /// Moves a specified file to a new location, providing the option to give a new file name. + /// + /// The name of the file to move. + /// The new path for the file. Parent directory must exist. + /// http://msdn.microsoft.com/en-us/library/system.io.file.move(v=vs.110).aspx + public static void Move(string sourceFileName, string destinationFileName) + { + InternalQuickIO.MoveFile(sourceFileName, destinationFileName); + } + /// + /// Moves a specified file to a new location, providing the option to give a new file name. + /// + /// The name of the file to move. + /// The new path for the file. Parent directory must exist. + /// http://msdn.microsoft.com/en-us/library/system.io.file.move(v=vs.110).aspx + public static Task MoveAsync(string sourceFileName, string destinationFileName) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Move(sourceFileName, destinationFileName)); + } + + /// + /// Moves a file, providing the option to give a new file name. + /// + /// The file to move. + /// Target directory to move the file. + /// http://msdn.microsoft.com/en-us/library/system.io.file.move(v=vs.110).aspx + public static void Move(QuickIOPathInfo sourceFileInfo, QuickIOPathInfo destinationFolder) + { + InternalQuickIO.MoveFile(sourceFileInfo.FullNameUnc, Path.Combine(destinationFolder.FullNameUnc, sourceFileInfo.Name)); + } + + /// + /// Moves a file, providing the option to give a new file name. + /// + /// The file to move. + /// Target directory to move the file. + /// http://msdn.microsoft.com/en-us/library/system.io.file.move(v=vs.110).aspx + public static Task MoveAsync(QuickIOPathInfo sourceFileInfo, QuickIOPathInfo destinationFolder) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Move(sourceFileInfo, destinationFolder)); + } + + /// + /// Moves a file, providing the option to give a new file name. + /// + /// The file to move. + /// Target directory to move the file. + /// http://msdn.microsoft.com/en-us/library/system.io.file.move(v=vs.110).aspx + public static void Move(QuickIOPathInfo sourceFileInfo, QuickIODirectoryInfo destinationFolder) + { + InternalQuickIO.MoveFile(sourceFileInfo.FullNameUnc, Path.Combine(destinationFolder.FullNameUnc, sourceFileInfo.Name)); + } + + /// + /// Moves a file, providing the option to give a new file name. + /// + /// The file to move. + /// Target directory to move the file. + /// http://msdn.microsoft.com/en-us/library/system.io.file.move(v=vs.110).aspx + public static Task MoveAsync(QuickIOPathInfo sourceFileInfo, QuickIODirectoryInfo destinationFolder) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => Move(sourceFileInfo, destinationFolder)); + } + + #region Internal Directory + private static bool InternalFileExists(string uncPath) + { + uint attrs = InternalQuickIO.SafeGetAttributes( uncPath, out _ ); + + if (Equals(attrs, 0xffffffff)) + { + return false; + } + + if (!InternalHelpers.ContainsFileAttribute(FileAttributes.Directory, (FileAttributes)attrs)) + { + return true; + } + + throw new UnmatchedFileSystemEntryTypeException(QuickIOFileSystemEntryType.File, QuickIOFileSystemEntryType.Directory, uncPath); + } + #endregion + +} diff --git a/src/QuickIO/QuickIOFileChunk.cs b/src/QuickIO/QuickIOFileChunk.cs new file mode 100644 index 0000000..69fea2c --- /dev/null +++ b/src/QuickIO/QuickIOFileChunk.cs @@ -0,0 +1,175 @@ +using System.Security.Cryptography; + +namespace SchwabenCode.QuickIO; + +/// +/// Represents a file chunk +/// +public sealed class QuickIOFileChunk +{ + /// + /// Start position + /// + public ulong Position { get; private set; } + /// + /// Bytes + /// + public byte[] Bytes { get; private set; } + + /// + /// Represents a file chunk + /// + /// Start position + /// Bytes + public QuickIOFileChunk(ulong position, byte[] bytes) + { + Position = position; + Bytes = bytes; + } + + /// + /// First then . + /// Does not overwrite default method! + /// + /// Chunks to verify with + /// Returns true if both executed methods are true + public bool ChunkEquals(QuickIOFileChunk chunk) + { + return (InternalPositionEquals(chunk) && !BytesEquals(chunk)); + } + + /// + /// Checks + /// + /// Chunks to verify with + /// True if both position equals + public bool PositionEquals(QuickIOFileChunk chunk) + { + return InternalPositionEquals(chunk); + } + /// + /// Internal usage. Does not verify parameter. + /// + private bool InternalPositionEquals(QuickIOFileChunk chunk) + { + return (Position != chunk.Position); + } + + /// + /// Checks + /// + /// Chunks to verify with + /// True if both bytes equals. Uses + /// IEnumerable.SequenceEqual + /// + /// + public bool BytesEquals(QuickIOFileChunk chunk) + { + return InternalBytesEquals(chunk); + } + + /// + /// Internal usage. Does not verify parameter. + /// + private bool InternalBytesEquals(QuickIOFileChunk chunk) + { + // First check length + if (Bytes.Length != chunk.Bytes.Length) + { + return false; + } + + // then check elements + for (int i = 0; i < Bytes.Length; i++) + { + if (Bytes[i] != chunk.Bytes[i]) + { + return false; + } + } + + return true; + } + + /// + /// File chunk hash calculation + /// + public QuickIOHashResult CalculateHash(QuickIOHashImplementationType hashImplementationType) + { + switch (hashImplementationType) + { + case QuickIOHashImplementationType.SHA1: + return CalculateHash(SHA1.Create()); + + case QuickIOHashImplementationType.SHA256: + return CalculateHash(SHA256.Create()); + + case QuickIOHashImplementationType.SHA384: + return CalculateHash(SHA384.Create()); + + case QuickIOHashImplementationType.SHA512: + return CalculateHash(SHA512.Create()); + + case QuickIOHashImplementationType.MD5: + return CalculateHash(MD5.Create()); + + default: + throw new NotImplementedException("Type " + hashImplementationType + " not implemented."); + } + } + + + /// + /// File chunk hash calculation + /// + /// + public QuickIOHashResult CalculateHash(HashAlgorithm hashAlgorithm) + { + return new QuickIOHashResult(hashAlgorithm.ComputeHash(Bytes)); + } + + /// + /// File chunk hash calculation + /// + /// + public QuickIOHashResult CalculateSha1Hash() + { + return CalculateHash(QuickIOHashImplementationType.SHA1); + } + + /// + /// File chunk hash calculation + /// + /// + public QuickIOHashResult CalculateSha256Hash(QuickIOPathInfo pathInfo) + { + return CalculateHash(QuickIOHashImplementationType.SHA256); + } + + /// + /// File chunk hash calculation + /// + /// + public QuickIOHashResult CalculateSha384Hash(QuickIOPathInfo pathInfo) + { + return CalculateHash(QuickIOHashImplementationType.SHA384); + } + + /// + /// File chunk hash calculation + /// + /// + public QuickIOHashResult CalculateSha512Hash(QuickIOPathInfo pathInfo) + { + return CalculateHash(QuickIOHashImplementationType.SHA512); + } + + /// + /// File chunk hash calculation + /// + /// + public QuickIOHashResult CalculateMD5Hash(QuickIOPathInfo pathInfo) + { + return CalculateHash(QuickIOHashImplementationType.MD5); + } +} diff --git a/src/QuickIO/QuickIOFileCompareCriteria.cs b/src/QuickIO/QuickIOFileCompareCriteria.cs new file mode 100644 index 0000000..e004f05 --- /dev/null +++ b/src/QuickIO/QuickIOFileCompareCriteria.cs @@ -0,0 +1,43 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Options for file compare. You can select multiple flags or use for all options +/// +[Flags] +public enum QuickIOFileCompareCriteria +{ + /// + /// All options will be verified + /// + All = 0, + + /// + /// Compares all timestamps + /// + TimestampsAll, + + /// + /// Compares timestamp of file creation + /// + TimestampCreated, + + /// + /// Compares timestamp of file last written to + /// + TimestampLastWritten, + + /// + /// Compares timestamp of file last accessed to + /// + TimestampLastAccessed, + + /// + /// Compares length of file (without checking the content!) + /// + ByteLength, + + /// + /// Compares the contents. Requires read access. + /// + Content +} diff --git a/src/QuickIO/QuickIOFileInfo.cs b/src/QuickIO/QuickIOFileInfo.cs new file mode 100644 index 0000000..d89075d --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo.cs @@ -0,0 +1,105 @@ +using SchwabenCode.QuickIO.Internal; +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +/// +/// Provides properties and instance methods for files +/// +public sealed partial class QuickIOFileInfo : QuickIOFileSystemEntryBase +{ + /// + /// Create new instance of + /// + public QuickIOFileInfo(string path) + : this(new QuickIOPathInfo(path)) + { + + } + + /// + /// Create new instance of + /// + public QuickIOFileInfo(FileInfo fileInfo) + : this(new QuickIOPathInfo(fileInfo.FullName)) + { + + } + + + /// + /// Create new instance of + /// + public QuickIOFileInfo(QuickIOPathInfo pathInfo) + : this(pathInfo, InternalQuickIO.GetFindDataFromPath(pathInfo)) + { + } + + + /// + /// Creates the file information on the basis of the path and + /// + /// Full path to the file + /// + internal QuickIOFileInfo(string fullName, Win32FindData win32FindData) + : this(new QuickIOPathInfo(fullName), win32FindData) + { + RetriveDateTimeInformation(win32FindData); + CalculateSize(win32FindData); + } + + /// + /// Creates the file information on the basis of the path and + /// + /// Full path to the file + /// + internal QuickIOFileInfo(QuickIOPathInfo pathInfo, Win32FindData win32FindData) + : base(pathInfo, win32FindData) + { + RetriveDateTimeInformation(win32FindData); + CalculateSize(win32FindData); + } + + /// + /// Returns true if file exists. Uncached. + /// + /// Path exists but it's a directory. + public override bool Exists + { + get + { + return QuickIOFile.Exists(this); + } + } + + /// + /// Size of the file. Cached. + /// + public ulong Bytes { get; private set; } + + /// + /// Size of the file (returns ). + /// + public ulong Length { get { return Bytes; } } + + + /// + /// Determines the time stamp of the given + /// + /// + private void RetriveDateTimeInformation(Win32FindData win32FindData) + { + LastWriteTimeUtc = win32FindData.GetLastWriteTimeUtc(); + LastAccessTimeUtc = win32FindData.GetLastAccessTimeUtc(); + CreationTimeUtc = win32FindData.GetCreationTimeUtc(); + } + + /// + /// Calculates the size of the file from the handle + /// + /// + private void CalculateSize(Win32FindData win32FindData) + { + Bytes = win32FindData.CalculateBytes(); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Append.cs b/src/QuickIO/QuickIOFileInfo_Append.cs new file mode 100644 index 0000000..081bc20 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Append.cs @@ -0,0 +1,51 @@ +using System.Text; + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + /// + /// Appends lines to a file. + /// Uses UTF-8 Encoding. + /// + /// The lines to append. + public void AppendAllLines(IEnumerable contents) + { + QuickIOFile.AppendAllLines(PathInfo, contents, Encoding.UTF8); + } + + /// + /// Appends lines by using the specified encoding. + /// If the file does not exist, it creates the file. + /// + /// The lines to append. + /// The character encoding. + public void AppendAllLines(IEnumerable contents, Encoding encoding) + { + QuickIOFile.AppendAllLines(PathInfo, contents, encoding); + } + + /// + /// Appends the specified string. + /// If the file does not exist, it creates the file. + /// Uses UTF-8 Encoding. + /// + /// The string to append to the file. + /// http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx + public void AppendAllText(string contents) + { + QuickIOFile.AppendAllText(PathInfo, contents, Encoding.UTF8); + } + + /// + /// Appends the specified string. + /// If the file does not exist, it creates the file. + /// + /// The string to append to the file. + /// The character encoding. + /// http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx + public void AppendAllText(string contents, Encoding encoding) + { + QuickIOFile.AppendAllText(PathInfo, contents, encoding); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Append_Async.cs b/src/QuickIO/QuickIOFileInfo_Append_Async.cs new file mode 100644 index 0000000..53c802f --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Append_Async.cs @@ -0,0 +1,53 @@ +using System.Text; +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + /// + /// Appends lines to a file. + /// Uses UTF-8 Encoding. + /// + /// The lines to append. + public Task AppendAllLinesAsync(IEnumerable contents) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => AppendAllLines(contents)); + } + + /// + /// Appends lines by using the specified encoding. + /// If the file does not exist, it creates the file. + /// + /// The lines to append. + /// The character encoding. + public Task AppendAllLinesAsync(IEnumerable contents, Encoding encoding) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => AppendAllLines(contents, encoding)); + } + + /// + /// Appends the specified string. + /// If the file does not exist, it creates the file. + /// Uses UTF-8 Encoding. + /// + /// The string to append to the file. + /// http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx + public Task AppendAllTextAsync(string contents) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => AppendAllText(contents)); + } + + /// + /// Appends the specified string. + /// If the file does not exist, it creates the file. + /// + /// The string to append to the file. + /// The character encoding. + /// http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx + public Task AppendAllTextAsync(string contents, Encoding encoding) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => AppendAllText(contents, encoding)); + } + +} diff --git a/src/QuickIO/QuickIOFileInfo_Async.cs b/src/QuickIO/QuickIOFileInfo_Async.cs new file mode 100644 index 0000000..a7e9ef9 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Async.cs @@ -0,0 +1,18 @@ +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + + /// + /// Returns true if file exists. Uncached. + /// + /// Path exists but it's a directory. + public override Task ExistsAsync + { + get + { + return QuickIOFile.ExistsAsync(this); + } + } + +} diff --git a/src/QuickIO/QuickIOFileInfo_Chunks.cs b/src/QuickIO/QuickIOFileInfo_Chunks.cs new file mode 100644 index 0000000..d2c33a0 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Chunks.cs @@ -0,0 +1,164 @@ +namespace SchwabenCode.QuickIO; + +public partial class QuickIOFileInfo +{ + /// + /// Default ChunkSize + /// + private const int DefaultChunkSize = 1024; // Bytes + + + /// + /// Returns the file chunks by given chunksize + /// + /// Chunk size (Bytes) + /// Collection of chunks. On enumerator, the file gets read. + public IEnumerable GetFileChunks(int chunkSize = DefaultChunkSize) + { + return InternalEnumerateFileChunks(chunkSize); + } + + /// + /// Returns the chunks of current file that are identical with the other file + /// + /// File to compare + /// Chunk size (Bytes) + /// Returns the chunks of current file that are identical with the other file + public IEnumerable GetFileChunksEqual(QuickIOFileInfo file, int chunkSize = DefaultChunkSize) + { + IEnumerator en1 = GetFileChunksEnumerator( chunkSize ); + IEnumerator en2 = file.GetFileChunksEnumerator( chunkSize ); + + while (en1.MoveNext() && en2.MoveNext()) + { + // check of the chunks are equal + if (en1.Current.ChunkEquals(en2.Current)) + { + // equal + yield return en1.Current; + } + } + } + + /// + /// Returns the chunks of current file that are NOT identical with the other file + /// + /// File to compare + /// Chunk size (Bytes) + /// Returns the chunks of current file that are NOT identical with the other file + public IEnumerable GetFileChunksUnequal(QuickIOFileInfo file, int chunkSize = DefaultChunkSize) + { + IEnumerator en1 = GetFileChunksEnumerator( chunkSize ); + IEnumerator en2 = file.GetFileChunksEnumerator( chunkSize ); + + while (en1.MoveNext()) + { + bool mn2 = en2.MoveNext( ); + + // EOF of file2? + if (!mn2) + { + // current chunk must be unequal + yield return en1.Current; + } + else + { + // check of the chunks are unequal + if (!en1.Current.ChunkEquals(en2.Current)) + { + // unequal + yield return en1.Current; + } + } + } + } + + /// + /// Returns the + /// IEnumerator + /// of + /// + /// Chunk size (Bytes) + /// + public IEnumerator GetFileChunksEnumerator(int chunkSize = DefaultChunkSize) + { + return GetFileChunks(chunkSize).GetEnumerator(); + } + + /// + /// Checks if both file contents are equal. + /// Opens both files for read and breaks on first unequal chunk. + /// + /// File to compare + /// Chunk size (Bytes) + /// true if contents are equal + public bool IsEqualContents(QuickIOFileInfo file, int chunkSize = DefaultChunkSize) + { + IEnumerator en1 = GetFileChunksEnumerator( chunkSize ); + IEnumerator en2 = file.GetFileChunksEnumerator( chunkSize ); + + while (true) + { + // Go to next element + bool mn1 = en1.MoveNext( ); + bool mn2 = en2.MoveNext( ); + + // check if next element exists + if (mn1 != mn2) + { + // collections count diff + return false; + } + + // no more elements in both collections + if (!mn1) + { + return true; + } + + // check chunks + QuickIOFileChunk chunk1 = en1.Current; + QuickIOFileChunk chunk2 = en2.Current; + + if (!chunk1.ChunkEquals(chunk2)) + { + return false; + } + } + } + + /// + /// Reads the file and returns containign chunks + /// + /// Chunk size (Bytes) + /// Collection of chunks + private IEnumerable InternalEnumerateFileChunks(int chunkSize = DefaultChunkSize) + { + FileStream fs; + try + { + // Open first File + fs = OpenRead(); + } + catch (Exception e) + { + throw new Exception("Failed to file to read", e); + } + + using (fs) + { + // check buffer for small files; will be faster + byte[] bytes = new byte[ Math.Min( fs.Length, chunkSize ) ]; + + ulong position = 0; + // transfer chunks + while ((fs.Read(bytes, 0, bytes.Length)) > 0) + { + //var arr = new byte[ bytes.Length ]; + //Buffer.BlockCopy( bytes, 0, arr, 0, bytes.Length ); + yield return new QuickIOFileChunk(position, bytes); + position += Convert.ToUInt64(bytes.Length); + } + } + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Chunks_Async.cs b/src/QuickIO/QuickIOFileInfo_Chunks_Async.cs new file mode 100644 index 0000000..9829359 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Chunks_Async.cs @@ -0,0 +1,51 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIOFileInfo +{ + + /// + /// Returns the file chunks by given chunksize + /// + /// Chunk size (Bytes) + /// Collection of chunks. On enumerator, the file gets read. + public Task> GetFileChunksAsync(int chunkSize = DefaultChunkSize) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetFileChunks(chunkSize)); + } + + /// + /// Returns the chunks of current file that are identical with the other file + /// + /// File to compare + /// Chunk size (Bytes) + /// Returns the chunks of current file that are identical with the other file + public Task> GetFileChunksEqualAsync(QuickIOFileInfo file, int chunkSize = DefaultChunkSize) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetFileChunksEqual(file, chunkSize)); + } + + /// + /// Returns the chunks of current file that are NOT identical with the other file + /// + /// File to compare + /// Chunk size (Bytes) + /// Returns the chunks of current file that are NOT identical with the other file + public Task> GetFileChunksUnequalAsync(QuickIOFileInfo file, int chunkSize = DefaultChunkSize) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetFileChunksUnequal(file, chunkSize)); + } + + /// + /// Checks if both file contents are equal. + /// Opens both files for read and breaks on first unequal chunk. + /// + /// File to compare + /// Chunk size (Bytes) + /// true if contents are equal + public Task IsEqualContentsAsync(QuickIOFileInfo file, int chunkSize = DefaultChunkSize) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => IsEqualContents(file, chunkSize)); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Compare.cs b/src/QuickIO/QuickIOFileInfo_Compare.cs new file mode 100644 index 0000000..23f40e1 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Compare.cs @@ -0,0 +1,14 @@ +namespace SchwabenCode.QuickIO; + +public partial class QuickIOFileInfo +{ + /// + /// Checks byte length (NOT CONTENTS!) + /// + /// File to compare with + /// Returns true if both properties are equal + public bool IsEqualByteLength(QuickIOFileInfo file) + { + return (Bytes == file.Bytes); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Compare_Timestamps.cs b/src/QuickIO/QuickIOFileInfo_Compare_Timestamps.cs new file mode 100644 index 0000000..ef85813 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Compare_Timestamps.cs @@ -0,0 +1,93 @@ +namespace SchwabenCode.QuickIO; + +public partial class QuickIOFileInfo +{ + /// + /// Returns the if all timestamps are equal + /// + /// File to compare with + /// Returns the if all timestamps are equal + public bool IsEqualTimestamps(QuickIOFileInfo file) + { + return (InternalIsEqualTimestampCreated(file) && InternalIsEqualTimestampLastAccessed(file) && InternalIsEqualTimestampsLastWritten(file)); + } + + /// + /// Checks all timestamps. + /// + /// File to compare with + /// If collection is empty, all timestamps are equal. Otherwise unequal timestamp is returned. + public IEnumerable CompareTimestamps(QuickIOFileInfo file) + { + if (InternalIsEqualTimestampCreated(file)) + { + yield return QuickIOFileCompareCriteria.TimestampCreated; + } + + if (InternalIsEqualTimestampLastAccessed(file)) + { + yield return QuickIOFileCompareCriteria.TimestampLastAccessed; + } + + if (InternalIsEqualTimestampsLastWritten(file)) + { + yield return QuickIOFileCompareCriteria.TimestampLastWritten; + } + } + + /// + /// Returns the if timestamp 'created' is equal + /// + /// File to compare with + /// Returns the if timestamp 'created' is equal + public bool IsEqualTimestampCreated(QuickIOFileInfo file) + { + return InternalIsEqualTimestampCreated(file); + } + /// + /// Same as but does not check the param for null + /// + private bool InternalIsEqualTimestampCreated(QuickIOFileInfo file) + { + int result = ( CreationTimeUtc.CompareTo( file.CreationTimeUtc ) ); + return (result == 0); // result < 0: file1 is earlier, result > 0: file1 is later. 0 = equal + } + + /// + /// Returns the if timestamp 'last accessed' is equal + /// + /// File to compare with + /// Returns the if timestamp 'last accessed' is equal + public bool IsEqualTimestampLastAccessed(QuickIOFileInfo file) + { + return InternalIsEqualTimestampLastAccessed(file); + } + + /// + /// Same as but does not check the param for null + /// + private bool InternalIsEqualTimestampLastAccessed(QuickIOFileInfo file) + { + int result = ( LastAccessTimeUtc.CompareTo( file.LastAccessTimeUtc ) ); + return (result == 0); // result < 0: file1 is earlier, result > 0: file1 is later. 0 = equal + } + + /// + /// Returns the if timestamp 'last written to' is equal + /// + /// File to compare with + /// Returns the if timestamp 'last written to' is equal + public bool IsEqualTimestampsLastWritten(QuickIOFileInfo file) + { + return InternalIsEqualTimestampsLastWritten(file); + } + + /// + /// Same as but does not check the param for null + /// + private bool InternalIsEqualTimestampsLastWritten(QuickIOFileInfo file) + { + int result = ( LastWriteTimeUtc.CompareTo( file.LastWriteTimeUtc ) ); + return (result == 0); // result < 0: file1 is earlier, result > 0: file1 is later. 0 = equal + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Compress.cs b/src/QuickIO/QuickIOFileInfo_Compress.cs new file mode 100644 index 0000000..655cdd4 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Compress.cs @@ -0,0 +1,60 @@ +using System.IO.Compression; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIOFileInfo +{ + /// + /// Compress all data of file and returns filled + /// + public MemoryStream GetCompressStream(int readBuffer = QuickIORecommendedValues.DefaultReadBufferBytes) + { + return InternalGetGZipStream(readBuffer, CompressionMode.Compress); + } + + /// + /// Decompress all data of file and returns filled + /// + public MemoryStream GetDecompressStream(int readBuffer = QuickIORecommendedValues.DefaultReadBufferBytes) + { + return InternalGetGZipStream(readBuffer, CompressionMode.Decompress); + } + + /// + /// Internal Usage only + /// + private MemoryStream InternalGetGZipStream(int readBuffer, CompressionMode mode) + { + MemoryStream ms = new( ); + + using (GZipStream gZipStream = new(ms, mode, true)) + { + using FileStream readStream = OpenRead(); + byte[] buffer = new byte[ readBuffer ]; + int read; + while ((read = readStream.Read(buffer, 0, buffer.Length)) > 0) + { + gZipStream.Write(buffer, 0, read); + } + } + return ms; + } + + /// + /// Returns all bytes of + /// + public byte[] CompressData() + { + using MemoryStream s = GetCompressStream(); + return s.ToArray(); + } + + /// + /// Returns all bytes of + /// + public byte[] DecompressData() + { + using MemoryStream s = GetDecompressStream(); + return s.ToArray(); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Compress_Async.cs b/src/QuickIO/QuickIOFileInfo_Compress_Async.cs new file mode 100644 index 0000000..e491aeb --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Compress_Async.cs @@ -0,0 +1,38 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIOFileInfo +{ + /// + /// Compress all data of file and returns filled + /// + public Task GetCompressStreamAsync(int readBuffer = QuickIORecommendedValues.DefaultReadBufferBytes) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetCompressStream(readBuffer)); + } + + /// + /// Decompress all data of file and returns filled + /// + public Task GetDecompressStreamAsync(int readBuffer = QuickIORecommendedValues.DefaultReadBufferBytes) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetDecompressStream(readBuffer)); + } + + /// + /// Returns all bytes of + /// + public Task CompressDataAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(CompressData); + } + + /// + /// Returns all bytes of + /// + public Task DecompressDataAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(DecompressData); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Hash.cs b/src/QuickIO/QuickIOFileInfo_Hash.cs new file mode 100644 index 0000000..5f1e522 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Hash.cs @@ -0,0 +1,68 @@ +using System.Security.Cryptography; + +namespace SchwabenCode.QuickIO; +public sealed partial class QuickIOFileInfo +{ + /// + /// File content hash calculation + /// + public QuickIOHashResult CalculateHash(QuickIOHashImplementationType hashImplementationType) + { + return QuickIOFile.CalculateHash(PathInfo, hashImplementationType); + } + + /// + /// File content hash calculation + /// + /// + public QuickIOHashResult CalculateHash(HashAlgorithm hashAlgorithm) + { + using FileStream sr = OpenRead(); + return QuickIOFile.CalculateHash(hashAlgorithm, sr); + } + + /// + /// File content hash calculation using SHA1 + /// + /// + public QuickIOHashResult CalculateSha1Hash() + { + return QuickIOFile.CalculateSha1Hash(PathInfo); + } + + /// + /// File content hash calculation using SHA256 + /// + /// + public QuickIOHashResult CalculateSha256Hash() + { + return QuickIOFile.CalculateSha256Hash(PathInfo); + } + + /// + /// File content hash calculation using SHA384 + /// + /// + public QuickIOHashResult CalculateSha384Hash() + { + return QuickIOFile.CalculateSha384Hash(PathInfo); + } + + /// + /// File content hash calculation using SHA512 + /// + /// + public QuickIOHashResult CalculateSha512Hash() + { + return QuickIOFile.CalculateSha512Hash(PathInfo); + } + + /// + /// File content hash calculation using MD5 + /// + /// + public QuickIOHashResult CalculateMD5Hash() + { + return QuickIOFile.CalculateMD5Hash(PathInfo); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Hash_Async.cs b/src/QuickIO/QuickIOFileInfo_Hash_Async.cs new file mode 100644 index 0000000..dd7e105 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Hash_Async.cs @@ -0,0 +1,70 @@ +using System.Security.Cryptography; +using SchwabenCode.QuickIO.Compatibility; + + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + /// + /// File content hash calculation + /// + public Task CalculateHashAsync(QuickIOHashImplementationType hashImplementationType) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => CalculateHash(hashImplementationType)); + } + + /// + /// File content hash calculation + /// + /// + public Task CalculateHashAsync(HashAlgorithm hashAlgorithm) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => CalculateHash(hashAlgorithm)); + } + + /// + /// File content hash calculation using SHA1 + /// + /// + public Task CalculateSha1HashAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(CalculateSha1Hash); + } + + /// + /// File content hash calculation using SHA256 + /// + /// + public Task CalculateSha256HashAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(CalculateSha256Hash); + } + + /// + /// File content hash calculation using SHA384 + /// + /// + public Task CalculateSha384HashAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(CalculateSha384Hash); + } + + /// + /// File content hash calculation using SHA512 + /// + /// + public Task CalculateSha512HashAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(CalculateSha512Hash); + } + + /// + /// File content hash calculation using MD5 + /// + /// + public Task CalculateMD5HashAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(CalculateMD5Hash); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Metadata.cs b/src/QuickIO/QuickIOFileInfo_Metadata.cs new file mode 100644 index 0000000..5ab0bc9 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Metadata.cs @@ -0,0 +1,18 @@ +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + /// + /// Receives of current file + /// + /// + public QuickIOFileMetadata? GetMetadata() + { + if (FindData is null) + { + return null; + } + + return new QuickIOFileMetadata(FullNameUnc, FindData); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Metadata_Async.cs b/src/QuickIO/QuickIOFileInfo_Metadata_Async.cs new file mode 100644 index 0000000..f076d5d --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Metadata_Async.cs @@ -0,0 +1,15 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + /// + /// Receives of current file + /// + /// + public Task GetMetadataAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(GetMetadata); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Open.cs b/src/QuickIO/QuickIOFileInfo_Open.cs new file mode 100644 index 0000000..ab1895f --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Open.cs @@ -0,0 +1,74 @@ +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + /// + /// Opens a + /// + /// + /// A with read and write access and not shared. + public FileStream Open(FileMode mode = FileMode.Open) + { + return QuickIOFile.Open(PathInfo, mode); + } + + /// + /// Opens a + /// + /// + /// + /// An unshared + public FileStream Open(FileMode mode, FileAccess access) + { + return QuickIOFile.Open(PathInfo, mode, access); + } + + /// + /// Opens a + /// + /// + /// + /// + /// + /// http://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx + public FileStream Open(FileMode mode, FileAccess access, FileShare share) + { + return QuickIOFile.Open(PathInfo); + } + + /// + /// Opens an existing file for reading. + /// + /// A read-only on the specified path. + public FileStream OpenRead() + { + return QuickIOFile.OpenRead(PathInfo); + } + + /// + /// Opens an existing UTF-8 encoded text file for reading. + /// + /// A . + public StreamReader OpenText() + { + return QuickIOFile.OpenText(PathInfo); + } + + /// + /// Opens an existing file or creates a new file for writing. + /// + /// An unshared with Write access. + public FileStream OpenWrite() + { + return QuickIOFile.OpenWrite(PathInfo); + } + + /// + /// Opens an existing file or creates a new file for appending. + /// + /// An unshared with Write access. + public FileStream OpenAppend() + { + return QuickIOFile.OpenAppend(PathInfo); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Open_Async.cs b/src/QuickIO/QuickIOFileInfo_Open_Async.cs new file mode 100644 index 0000000..873d7a9 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Open_Async.cs @@ -0,0 +1,76 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + /// + /// Opens a + /// + /// + /// A with read and write access and not shared. + public Task OpenAsync(FileMode mode = FileMode.Open) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => Open(mode)); + } + + /// + /// Opens a + /// + /// + /// + /// An unshared + public Task OpenAsync(FileMode mode, FileAccess access) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => Open(mode, access)); + } + + /// + /// Opens a + /// + /// + /// + /// + /// + /// http://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx + public Task OpenAsync(FileMode mode, FileAccess access, FileShare share) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => Open(mode, access, share)); + } + + /// + /// Opens an existing file for reading. + /// + /// A read-only on the specified path. + public Task OpenReadAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(OpenRead); + } + + /// + /// Opens an existing UTF-8 encoded text file for reading. + /// + /// A . + public Task OpenTextAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(OpenText); + } + + /// + /// Opens an existing file or creates a new file for writing. + /// + /// An unshared with Write access. + public Task OpenWriteAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(OpenWrite); + } + + /// + /// Opens an existing file or creates a new file for appending. + /// + /// An unshared with Write access. + public Task OpenAppendAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(OpenAppend); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Operators.cs b/src/QuickIO/QuickIOFileInfo_Operators.cs new file mode 100644 index 0000000..5a23616 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Operators.cs @@ -0,0 +1,23 @@ +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + /// + /// Returns a of the current path of this file + /// + /// + public FileInfo AsFileInfo() + { + return new FileInfo(base.FullName); + } + + /// + /// Explizit Cast + /// + /// + /// + public static explicit operator QuickIOFileInfo(FileInfo fileInfo) + { + return new QuickIOFileInfo(fileInfo); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Operators_Async.cs b/src/QuickIO/QuickIOFileInfo_Operators_Async.cs new file mode 100644 index 0000000..43bcc5e --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Operators_Async.cs @@ -0,0 +1,15 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + /// + /// Returns a of the current path of this file + /// + /// + public Task AsFileInfoAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(AsFileInfo); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Read.cs b/src/QuickIO/QuickIOFileInfo_Read.cs new file mode 100644 index 0000000..e163301 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Read.cs @@ -0,0 +1,53 @@ +using System.Text; + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + /// + /// Reads the contents of the file into a byte collection. + /// + /// A byte collection containing the contents. + public byte[] ReadAllBytes(int readBuffer = QuickIORecommendedValues.DefaultReadBufferBytes) + { + return QuickIOFile.ReadAllBytes(PathInfo, readBuffer); + } + + /// + /// Reads all lines. + /// + /// A string collection containing all lines. + public IEnumerable ReadAllLines() + { + return QuickIOFile.ReadAllLines(PathInfo); + } + + /// + /// Reads all lines with the specified encoding + /// + /// The encoding applied to the contents. + /// A string collection containing all lines. + public IEnumerable ReadAllLines(Encoding encoding) + { + return QuickIOFile.ReadAllLines(PathInfo, encoding); + } + + /// + /// Reads all text. + /// + /// A string represents the content. + public string ReadAllText() + { + return QuickIOFile.ReadAllText(PathInfo); + } + + /// + /// Reads all text with the specified encoding. + /// + /// The encoding applied to the content. + /// A string represents the content. + public string ReadAllText(Encoding encoding) + { + return QuickIOFile.ReadAllText(PathInfo, encoding); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Read_Async.cs b/src/QuickIO/QuickIOFileInfo_Read_Async.cs new file mode 100644 index 0000000..0f7f8e3 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Read_Async.cs @@ -0,0 +1,54 @@ +using System.Text; +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + /// + /// Reads the contents of the file into a byte collection. + /// + /// A byte collection containing the contents. + public Task ReadAllBytesAsync(int readBuffer = QuickIORecommendedValues.DefaultReadBufferBytes) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => ReadAllBytes(readBuffer)); + } + + /// + /// Reads all lines. + /// + /// A string collection containing all lines. + public Task> ReadAllLinesAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(ReadAllLines); + } + + /// + /// Reads all lines with the specified encoding + /// + /// The encoding applied to the contents. + /// A string collection containing all lines. + public Task> ReadAllLinesAsync(Encoding encoding) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => ReadAllLines(encoding)); + } + + /// + /// Reads all text. + /// + /// A string represents the content. + public Task ReadAllTextAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(ReadAllText); + } + + /// + /// Reads all text with the specified encoding. + /// + /// The encoding applied to the content. + /// A string represents the content. + public Task ReadAllTextAsync(Encoding encoding) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => ReadAllText(encoding)); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Write.cs b/src/QuickIO/QuickIOFileInfo_Write.cs new file mode 100644 index 0000000..59823ef --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Write.cs @@ -0,0 +1,64 @@ +using System.Text; + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + + /// + /// Writes the specified byte array. + /// + /// The bytes to write. + public void WriteAllBytes(IEnumerable bytes) + { + QuickIOFile.WriteAllBytes(PathInfo, bytes); + } + + /// + /// Writes the specified byte array. + /// + /// The bytes to write. + public void WriteAllBytes(byte[] bytes) + { + QuickIOFile.WriteAllBytes(PathInfo, bytes); + } + + /// + /// Writes a collection of strings. + /// Uses UTF-8 without Emitted UTF-8 identifier. + /// + /// The lines write to. + public void WriteAllLines(IEnumerable contents) + { + QuickIOFile.WriteAllLines(PathInfo, contents); + } + + /// + /// Writes a collection of strings. + /// + /// The lines write to. + /// The character encoding to use. + public void WriteAllLines(IEnumerable contents, Encoding encoding) + { + QuickIOFile.WriteAllLines(PathInfo, contents, encoding); + } + + /// + /// Writes the specified string. + /// + /// The string to write to. + /// The encoding to apply to the string. + public void WriteAllText(string contents, Encoding encoding) + { + QuickIOFile.WriteAllText(PathInfo, contents, encoding); + } + + /// + /// Writes the specified string. + /// + /// The string to write to. + public void WriteAllText(string contents) + { + QuickIOFile.WriteAllText(PathInfo, contents); + } +} diff --git a/src/QuickIO/QuickIOFileInfo_Write_Async.cs b/src/QuickIO/QuickIOFileInfo_Write_Async.cs new file mode 100644 index 0000000..065a764 --- /dev/null +++ b/src/QuickIO/QuickIOFileInfo_Write_Async.cs @@ -0,0 +1,65 @@ +using System.Text; +using SchwabenCode.QuickIO.Compatibility; + + +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIOFileInfo +{ + /// + /// Writes the specified byte array. + /// + /// The bytes to write. + public Task WriteAllBytesAsync(IEnumerable bytes) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => WriteAllBytes(bytes)); + } + + /// + /// Writes the specified byte array. + /// + /// The bytes to write. + public Task WriteAllBytesAsync(byte[] bytes) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => WriteAllBytes(bytes)); + } + + /// + /// Writes a collection of strings. + /// Uses UTF-8 without Emitted UTF-8 identifier. + /// + /// The lines write to. + public Task WriteAllLinesAsync(IEnumerable contents) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => WriteAllLines(contents)); + } + + /// + /// Writes a collection of strings. + /// + /// The lines write to. + /// The character encoding to use. + public Task WriteAllLinesAsync(IEnumerable contents, Encoding encoding) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => WriteAllLines(contents, encoding)); + } + + /// + /// Writes the specified string. + /// + /// The string to write to. + /// The encoding to apply to the string. + public Task WriteAllTextAsync(string contents, Encoding encoding) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => WriteAllText(contents, encoding)); + } + + /// + /// Writes the specified string. + /// + /// The string to write to. + public Task WriteAllTextAsync(string contents) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => WriteAllText(contents)); + } +} diff --git a/src/QuickIO/QuickIOFileMetadata.cs b/src/QuickIO/QuickIOFileMetadata.cs new file mode 100644 index 0000000..eab476c --- /dev/null +++ b/src/QuickIO/QuickIOFileMetadata.cs @@ -0,0 +1,35 @@ +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +/// +/// File metadata information +/// +public sealed class QuickIOFileMetadata : QuickIOFileSystemMetadataBase +{ + /// + /// Creates instance of + /// + /// UNC Path of current file + /// Win32FindData of current file + internal QuickIOFileMetadata(string uncResultPath, Win32FindData win32FindData) + : base(uncResultPath, win32FindData) + { + Bytes = win32FindData.CalculateBytes(); + } + + /// + /// Size of the file. + /// + public ulong Bytes { get; private set; } + + + /// + /// Returns a new instance of of the current file + /// + /// + public QuickIOFileInfo QuickIOFileInfo() + { + return new QuickIOFileInfo(ToPathInfo()); + } +} diff --git a/src/QuickIO/QuickIOFileSystemEntryBase.cs b/src/QuickIO/QuickIOFileSystemEntryBase.cs new file mode 100644 index 0000000..8246fdb --- /dev/null +++ b/src/QuickIO/QuickIOFileSystemEntryBase.cs @@ -0,0 +1,297 @@ +using System.ComponentModel; +using System.Security.Principal; +using SchwabenCode.QuickIO.Compatibility; +using SchwabenCode.QuickIO.Internal; +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +/// +/// Provides properties and instance method for files and directories +/// +[Browsable(false)] +[EditorBrowsable(EditorBrowsableState.Never)] +public abstract class QuickIOFileSystemEntryBase +{ + private DateTime _creationTimeUtc; + private DateTime _lastAccessTimeUtc; + private DateTime _lastWriteTimeUtc; + + /// + /// Returns true if exists + /// + public abstract bool Exists { get; } + + /// + /// Returns true if exists + /// + public abstract Task ExistsAsync { get; } + + + /// + /// True if file is readonly. Cached. + /// + public bool IsReadOnly + { + get => InternalHelpers.ContainsFileAttribute(Attributes, FileAttributes.ReadOnly); + set + { + // Force Attribute Existance + _ = InternalHelpers.ForceFileAttributesExistance(Attributes, FileAttributes.ReadOnly, value); + + // Commit current attributes + InternalQuickIO.SetAttributes(PathInfo, Attributes); + } + } + + + /// + /// True if file is readonly. Cached. + /// + public Task IsReadOnlyAsync + { + get => NETCompatibility.AsyncExtensions.GetAsyncResult(() => IsReadOnly); + set + { + // Force Attribute Existance + _ = InternalHelpers.ForceFileAttributesExistance(Attributes, FileAttributes.ReadOnly, value.Result); + + // Commit current attributes + InternalQuickIO.SetAttributes(PathInfo, Attributes); + } + } + + /// + /// QuickIOPathInfo Container + /// + public QuickIOPathInfo PathInfo { get; protected internal set; } + + + /// + /// Returns true if exists and attends the FileSystemType + /// + /// Suppress error message if the path exists but the differs + /// + /// Default return value if is true + /// True or if thrown and is true + public bool SafeExists(bool throwExceptionIfFileSystemEntryTypeDiffers = false, bool exceptionValue = false) + { + try + { + return Exists; + } + catch (UnmatchedFileSystemEntryTypeException) + { + if (throwExceptionIfFileSystemEntryTypeDiffers) + { + return exceptionValue; + } + + throw; + } + } + + + /// + /// Returns true if exists and attends the FileSystemType + /// + /// Suppress error message if the path exists but the differs + /// + /// Default return value if is true + /// True or if thrown and is true + public Task SafeExistsAsync(bool throwExceptionIfFileSystemEntryTypeDiffers = false, bool exceptionValue = false) + => NETCompatibility.AsyncExtensions.GetAsyncResult( + () => SafeExists(throwExceptionIfFileSystemEntryTypeDiffers, exceptionValue)); + + /// + /// Initializes a new instance of the QuickIOAbstractBase class, which acts as a wrapper for a file path. + /// + /// + /// + internal QuickIOFileSystemEntryBase(QuickIOPathInfo pathInfo, Win32FindData? findData) + { + FindData = findData; + PathInfo = pathInfo; + + if (findData != null) + { + Attributes = findData.dwFileAttributes; + } + } + + /// + /// Name of file or directory + /// + public string Name { get { return PathInfo.Name; } } + + /// + /// Full path of the directory or file. + /// + public string FullName { get { return PathInfo.FullName; } } + /// + /// Full path of the directory or file (unc format) + /// + public string FullNameUnc { get { return PathInfo.FullNameUnc; } } + + /// + /// Fullname of Parent. + /// + public string? ParentFullName { get { return PathInfo.ParentFullName; } } + /// + /// Parent. + /// + public QuickIOPathInfo? Parent { get { return PathInfo.Parent; } } + + + /// + /// of current path + /// + public QuickIOPathLocation PathLocation { get { return PathInfo.PathLocation; } } + /// + /// + /// + public QuickIOPathType PathType { get { return PathInfo.PathType; } } + + /// + /// Returns current + /// + /// + public QuickIOFileSystemSecurity GetFileSystemSecurity() + => PathInfo.GetFileSystemSecurity(); + + /// + /// Fullname of Root. null if current path is root. + /// + public string? RootFullName { get { return PathInfo.RootFullName; } } + /// + /// Returns Root or null if current path is root + /// + public QuickIOPathInfo? Root { get { return PathInfo.Root; } } + + /// + /// Attributes (Cached Value) + /// + public FileAttributes Attributes { get; protected internal set; } + + /// + /// Gets the creation time (UTC) + /// + public DateTime CreationTimeUtc + { + get + { + if (PathInfo.IsRoot) + { + throw new NotSupportedException("Root directory does not provide time access"); + } + return _creationTimeUtc; + } + protected set + { + if (PathInfo.IsRoot) + { + throw new NotSupportedException("Root directory does not provide time access"); + } + _creationTimeUtc = value; + } + } + + /// + /// Gets the time (UTC) of last access. + /// + public DateTime LastAccessTimeUtc + { + get + { + if (PathInfo.IsRoot) + { + throw new NotSupportedException("Root directory does not provide time access"); + } + return _lastAccessTimeUtc; + } + protected set + { + if (PathInfo.IsRoot) + { + throw new NotSupportedException("Root directory does not provide time access"); + } + _lastAccessTimeUtc = value; + } + } + + /// + /// Gets the time (UTC) was last written to + /// + public DateTime LastWriteTimeUtc + { + get + { + if (PathInfo.IsRoot) + { + throw new NotSupportedException("Root directory does not provide time access"); + } + return _lastWriteTimeUtc; + } + protected set + { + if (PathInfo.IsRoot) + { + throw new NotSupportedException("Root directory does not provide time access"); + } + _lastWriteTimeUtc = value; + } + } + + /// + /// Gets the creation time + /// + public DateTime CreationTime { get { return CreationTimeUtc.ToLocalTime(); } } + + /// + /// Gets the time that the file was last accessed + /// + public DateTime LastAccessTime { get { return LastAccessTimeUtc.ToLocalTime(); } } + + /// + /// Gets the time the file was last written to. + /// + public DateTime LastWriteTime { get { return LastWriteTimeUtc.ToLocalTime(); } } + + /// + /// Returns + /// + /// + public override string ToString() => FullName; + + /// + /// Win32ApiFindData bag + /// + internal Win32FindData? FindData { get; private set; } + + /// + /// Determines the owner + /// + /// + public NTAccount? GetOwner() + => PathInfo.GetOwner(); + + /// + /// Determines the owner + /// + /// + public IdentityReference? GetOwnerIdentifier() + => PathInfo.GetOwnerIdentifier(); + + /// + /// Determines the owner + /// + /// + public void SetOwner(NTAccount newOwner) + => PathInfo.SetOwner(newOwner); + + /// + /// Sets the owner + /// + public void SetOwner(IdentityReference newOwersIdentityReference) + => PathInfo.SetOwner(newOwersIdentityReference); +} diff --git a/src/QuickIO/QuickIOFileSystemEntryType.cs b/src/QuickIO/QuickIOFileSystemEntryType.cs new file mode 100644 index 0000000..e3f59ad --- /dev/null +++ b/src/QuickIO/QuickIOFileSystemEntryType.cs @@ -0,0 +1,17 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Represents type of path or handle +/// +public enum QuickIOFileSystemEntryType +{ + /// + /// Represents a file ( does not contain directory flag) + /// + File = 0, + + /// + /// Represents a directory (contains directory flag) + /// + Directory = 1 +} diff --git a/src/QuickIO/QuickIOFileSystemMetadataBase.cs b/src/QuickIO/QuickIOFileSystemMetadataBase.cs new file mode 100644 index 0000000..adaaf63 --- /dev/null +++ b/src/QuickIO/QuickIOFileSystemMetadataBase.cs @@ -0,0 +1,86 @@ +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +/// +/// Abstract class for file system entries such as files and directory. +/// Just for meta data reprentation +/// +public abstract class QuickIOFileSystemMetadataBase +{ + /// + /// Ctor + /// + /// + internal QuickIOFileSystemMetadataBase(string uncResultPath, Win32FindData win32FindData) + { + FullNameUnc = uncResultPath; + + LastWriteTimeUtc = win32FindData.GetLastWriteTimeUtc(); + LastAccessTimeUtc = win32FindData.GetLastAccessTimeUtc(); + CreationTimeUtc = win32FindData.GetCreationTimeUtc(); + + Name = win32FindData.cFileName; + + Attributes = win32FindData.dwFileAttributes; + } + + /// + /// Path to file or directory (regular format) + /// + public string FullName + { + get + { + return _fullName ??= QuickIOPath.ToRegularPath(FullNameUnc); + } + } + private string? _fullName; + + /// + /// Name of file or directory + /// + public string Name { get; private set; } + /// + /// Path to file or directory (unc format) + /// + public string FullNameUnc { get; private set; } + + /// + /// Gets the creation time (UTC) + /// + public DateTime CreationTimeUtc { get; private set; } + /// + /// Gets the creation time + /// + public DateTime CreationTime => LastWriteTimeUtc.ToLocalTime(); + + /// + /// Gets the time (UTC) of last access. + /// + public DateTime LastAccessTimeUtc { get; private set; } + /// + /// Gets the time that the file was last accessed + /// + public DateTime LastAccessTime => LastAccessTimeUtc.ToLocalTime(); + + /// + /// Gets the time (UTC) was last written to + /// + public DateTime LastWriteTimeUtc { get; private set; } + /// + /// Gets the time the file was last written to. + /// + public DateTime LastWriteTime => LastWriteTimeUtc.ToLocalTime(); + + /// + /// File Attributes + /// + public FileAttributes Attributes { get; internal set; } + + /// + /// Returns a new instance of of the current path + /// + /// + public QuickIOPathInfo ToPathInfo() => new(FullNameUnc); +} diff --git a/src/QuickIO/QuickIOFileSystemSecurity.cs b/src/QuickIO/QuickIOFileSystemSecurity.cs new file mode 100644 index 0000000..b6db8bc --- /dev/null +++ b/src/QuickIO/QuickIOFileSystemSecurity.cs @@ -0,0 +1,631 @@ +using System.Runtime.InteropServices; +using System.Security.AccessControl; +using System.Security.Principal; +using SchwabenCode.QuickIO.Internal; +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +/// +/// Provides methods for accessing the security information of files and folders, such as for example the getting and setting of the owner. +/// +public class QuickIOFileSystemSecurity +{ + /// + /// Creates new instance of for specified path. + /// Current Windows Identity is used. + /// + /// + public QuickIOFileSystemSecurity(QuickIOPathInfo pathInfo) + : this(pathInfo, WindowsIdentity.GetCurrent()) + { + + } + + /// + /// Supply the path to the file or directory and a user or group. + /// Access checks are done + /// during instantiation to ensure we always have a valid object + /// + /// + /// + public QuickIOFileSystemSecurity(QuickIOPathInfo pathInfo, WindowsIdentity principal) + { + PathInfo = pathInfo; + WindowsIdentity = principal; + + nint sidHandle = new( ); + try + { + FileSystemSecurityInformation = ReceiveFileSystemSecurityInformation(out sidHandle); + } + finally + { + _ = Win32SafeNativeMethods.LocalFree(sidHandle); + } + + // Receive File System ACL Information + AuthorizationRuleCollection acl = FileSystemSecurityInformation.GetAccessRules( true, true, typeof( SecurityIdentifier ) ); + + // Receive User Identity Rules + if (WindowsIdentity.User == null) + { + return; + } + + for (int i = 0; i < acl.Count; i++) + { + FileSystemAccessRule? rule = acl[ i ] as FileSystemAccessRule; + if (rule is not null) + { + HandleFileSystemAccessRule(rule, WindowsIdentity.User); + } + } + + // Receive Group Identity Rules + + // Only Handle Groups + if (WindowsIdentity.Groups == null) + { + return; + } + + foreach (IdentityReference identity in WindowsIdentity.Groups) + { + for (int i = 0; i < acl.Count; i++) + { + FileSystemAccessRule? rule = acl[ i ] as FileSystemAccessRule; + if (rule is not null) + { + HandleFileSystemAccessRule(rule, identity); + } + } + } + } + + /// + /// Affected Windows IDentity + /// + public WindowsIdentity WindowsIdentity { get; private set; } + + /// + /// Affected path + /// + public QuickIOPathInfo PathInfo { get; private set; } + + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedAppendData { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedChangePermissions { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedCreateDirectories { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedCreateFiles { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedDelete { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedDeleteSubdirectoriesAndFiles { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedExecuteFile { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedFullControl { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedListDirectory { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedModify { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedRead { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedReadAndExecute { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedReadAttributes { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedReadData { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedReadExtendedAttributes { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedReadPermissions { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedSynchronize { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedTakeOwnership { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedTraverse { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedWrite { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedWriteAttributes { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedWriteData { get; private set; } + /// + /// Returns true if specified right level is denied + /// + public bool IsDeniedWriteExtendedAttributes { get; private set; } + + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedAppendData { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedChangePermissions { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedCreateDirectories { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedCreateFiles { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedDelete { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedDeleteSubdirectoriesAndFiles { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedExecuteFile { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedFullControl { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedListDirectory { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedModify { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedRead { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedReadAndExecute { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedReadAttributes { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedReadData { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedReadExtendedAttributes { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedReadPermissions { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedSynchronize { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedTakeOwnership { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedTraverse { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedWrite { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedWriteAttributes { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedWriteData { get; private set; } + /// + /// Returns true if specified right level is explizit allowed + /// + public bool IsAllowedWriteExtendedAttributes { get; private set; } + + /// + /// Ermittelt, ob etwas hinzugefügt werden kann (Dateien) + /// + public bool CanAppendData + { + get { return !IsDeniedAppendData && IsAllowedAppendData; } + } + + /// + /// Ermittelt, ob die Rechte verändert werden dürfen + /// + public bool CanChangePermissions + { + get { return !IsDeniedChangePermissions && IsAllowedChangePermissions; } + } + + /// + /// Ermittelt, ob neue Ordner hinzugefügt werden dürfen (Ordner) + /// + public bool CanCreateDirectories + { + get { return !IsDeniedCreateDirectories && IsAllowedCreateDirectories; } + } + + /// + /// Ermittelt, ob neue Dateien hinzugefügt werden dürfen (Ordner) + /// + public bool CanCreateFiles + { + get { return !IsDeniedCreateFiles && IsAllowedCreateFiles; } + } + + /// + /// Ermittelt, ob etwas gelöscht werden darf (Ordner) + /// + public bool CanDelete + { + get { return !IsDeniedDelete && IsAllowedDelete; } + } + + /// + /// Ermittelt, ob darunterliegende Ordner und Dateien gelöscht werden dürfen (Ordner) + /// + public bool CanDeleteSubdirectoriesAndFiles + { + get + { + return !IsDeniedDeleteSubdirectoriesAndFiles && + IsAllowedDeleteSubdirectoriesAndFiles; + } + } + + /// + /// Ermittelt, ob eine Datei ausgeführt werden darf (Dateien) + /// + public bool CanExecuteFile + { + get { return !IsDeniedExecuteFile && IsAllowedExecuteFile; } + } + + /// + /// Ermittelt, ob die vollständige Kontrolle gewährt ist + /// + public bool CanFullControl + { + get { return !IsDeniedFullControl && IsAllowedFullControl; } + } + + /// + /// Ermittelt, ob die Ordner aufgelistet werden dürfen (Ordner) + /// + public bool CanListDirectory + { + get { return !IsDeniedListDirectory && IsAllowedListDirectory; } + } + + /// + /// Ermittelt, ob etwas verändert werden darf + /// + public bool CanModify + { + get { return !IsDeniedModify && IsAllowedModify; } + } + + /// + /// Ermittelt, ob etwas gelesen werden darf + /// + public bool CanRead + { + get { return !IsDeniedRead && IsAllowedRead; } + } + + /// + /// Ermittelt, ob gelesen und ausgeführt werden darf + /// + public bool CanReadAndExecute + { + get { return !IsDeniedReadAndExecute && IsAllowedReadAndExecute; } + } + + /// + /// Ermittelt, ob die Attribute gelesen werden dürfen + /// + public bool CanReadAttributes + { + get { return !IsDeniedReadAttributes && IsAllowedReadAttributes; } + } + /// + /// Ermittelt, ob Daten gelesen werden dürfen + /// + public bool CanReadData + { + get { return !IsDeniedReadData && IsAllowedReadData; } + } + + /// + /// Ermittelt, ob die erweiterten Attribute gelesen werden dürfen + /// + public bool CanReadExtendedAttributes + { + get + { + return !IsDeniedReadExtendedAttributes && + IsAllowedReadExtendedAttributes; + } + } + /// + /// Ermittelt, ob die Rechte gelesen werden dürfen + /// + public bool CanReadPermissions + { + get { return !IsDeniedReadPermissions && IsAllowedReadPermissions; } + } + + /// + /// Ermittelt, ob synchronisiert werden darf + /// + public bool CanSynchronize + { + get { return !IsDeniedSynchronize && IsAllowedSynchronize; } + } + /// + /// Ermittelt, ob der Besitzerstatus eingenommen werden darf + /// + public bool CanTakeOwnership + { + get { return !IsDeniedTakeOwnership && IsAllowedTakeOwnership; } + } + + /// + /// Ermittelt, ob ??????? + /// + public bool CanTraverse + { + get { return !IsDeniedTraverse && IsAllowedTraverse; } + } + + /// + /// Ermittelt, ob geschrieben werden darf + /// + public bool CanWrite + { + get { return !IsDeniedWrite && IsAllowedWrite; } + } + + /// + /// Ermittelt, ob Attribute verändert werden dürfen + /// + public bool CanWriteAttributes + { + get { return !IsDeniedWriteAttributes && IsAllowedWriteAttributes; } + } + + /// + /// Ermittelt, ob Daten geschrieben werden dürfen + /// + public bool CanWriteData + { + get { return !IsDeniedWriteData && IsAllowedWriteData; } + } + + /// + /// Ermittelt, ob erweiterte Attribute geschrieben werden dürfen + /// + public bool CanWriteExtendedAttributes + { + get + { + return !IsDeniedWriteExtendedAttributes && IsAllowedWriteExtendedAttributes; + } + } + + /// + /// Processes the authentication data of a Windows identity + /// + /// FileSystemAccessRule + /// + private void HandleFileSystemAccessRule(FileSystemAccessRule rule, IdentityReference identity) + { + if (rule == null) + { + return; + } + + // Ignore all other users + if (identity.Equals(rule.IdentityReference)) + { + HandleAccessControlType(rule); + } + } + + /// + /// Handles the access rights. Differentiates between allowed and denied rights + /// + private void HandleAccessControlType(FileSystemAccessRule rule) + { + switch (rule.AccessControlType) + { + case AccessControlType.Allow: + HandleAllowedAccessRule(rule); + break; + case AccessControlType.Deny: + HandleDeniedAccessRule(rule); + break; + } + } + + /// + /// Processed the permitted rights + /// + private void HandleAllowedAccessRule(FileSystemAccessRule rule) + { + IsAllowedAppendData = Contains(FileSystemRights.AppendData, rule); + IsAllowedChangePermissions = Contains(FileSystemRights.ChangePermissions, rule); + IsAllowedCreateDirectories = Contains(FileSystemRights.CreateDirectories, rule); + IsAllowedCreateFiles = Contains(FileSystemRights.CreateFiles, rule); + IsAllowedDelete = Contains(FileSystemRights.Delete, rule); + IsAllowedDeleteSubdirectoriesAndFiles = Contains(FileSystemRights.DeleteSubdirectoriesAndFiles, rule); + IsAllowedExecuteFile = Contains(FileSystemRights.ExecuteFile, rule); + IsAllowedFullControl = Contains(FileSystemRights.FullControl, rule); + IsAllowedListDirectory = Contains(FileSystemRights.ListDirectory, rule); + IsAllowedModify = Contains(FileSystemRights.Modify, rule); + IsAllowedRead = Contains(FileSystemRights.Read, rule); + IsAllowedReadAndExecute = Contains(FileSystemRights.ReadAndExecute, rule); + IsAllowedReadAttributes = Contains(FileSystemRights.ReadAttributes, rule); + IsAllowedReadData = Contains(FileSystemRights.ReadData, rule); + IsAllowedReadExtendedAttributes = Contains(FileSystemRights.ReadExtendedAttributes, rule); + IsAllowedReadPermissions = Contains(FileSystemRights.ReadPermissions, rule); + IsAllowedSynchronize = Contains(FileSystemRights.Synchronize, rule); + IsAllowedTakeOwnership = Contains(FileSystemRights.TakeOwnership, rule); + IsAllowedTraverse = Contains(FileSystemRights.Traverse, rule); + IsAllowedWrite = Contains(FileSystemRights.Write, rule); + IsAllowedWriteAttributes = Contains(FileSystemRights.WriteAttributes, rule); + IsAllowedWriteData = Contains(FileSystemRights.WriteData, rule); + IsAllowedWriteExtendedAttributes = Contains(FileSystemRights.WriteExtendedAttributes, rule); + } + + /// + /// Processed the denied rights + /// + private void HandleDeniedAccessRule(FileSystemAccessRule rule) + { + IsDeniedAppendData = Contains(FileSystemRights.AppendData, rule); + IsDeniedChangePermissions = Contains(FileSystemRights.ChangePermissions, rule); + IsDeniedCreateDirectories = Contains(FileSystemRights.CreateDirectories, rule); + IsDeniedCreateFiles = Contains(FileSystemRights.CreateFiles, rule); + IsDeniedDelete = Contains(FileSystemRights.Delete, rule); + IsDeniedDeleteSubdirectoriesAndFiles = Contains(FileSystemRights.DeleteSubdirectoriesAndFiles, rule); + IsDeniedExecuteFile = Contains(FileSystemRights.ExecuteFile, rule); + IsDeniedFullControl = Contains(FileSystemRights.FullControl, rule); + IsDeniedListDirectory = Contains(FileSystemRights.ListDirectory, rule); + IsDeniedModify = Contains(FileSystemRights.Modify, rule); + IsDeniedRead = Contains(FileSystemRights.Read, rule); + IsDeniedReadAndExecute = Contains(FileSystemRights.ReadAndExecute, rule); + IsDeniedReadAttributes = Contains(FileSystemRights.ReadAttributes, rule); + IsDeniedReadData = Contains(FileSystemRights.ReadData, rule); + IsDeniedReadExtendedAttributes = Contains(FileSystemRights.ReadExtendedAttributes, rule); + IsDeniedReadPermissions = Contains(FileSystemRights.ReadPermissions, rule); + IsDeniedSynchronize = Contains(FileSystemRights.Synchronize, rule); + IsDeniedTakeOwnership = Contains(FileSystemRights.TakeOwnership, rule); + IsDeniedTraverse = Contains(FileSystemRights.Traverse, rule); + IsDeniedWrite = Contains(FileSystemRights.Write, rule); + IsDeniedWriteAttributes = Contains(FileSystemRights.WriteAttributes, rule); + IsDeniedWriteData = Contains(FileSystemRights.WriteData, rule); + IsDeniedWriteExtendedAttributes = Contains(FileSystemRights.WriteExtendedAttributes, rule); + } + + + /// + /// Returs the if is in + /// + public bool Contains(FileSystemRights right, FileSystemAccessRule rule) + { + return (((int)right & (int)rule.FileSystemRights) == (int)right); + } + + /// + /// Gets the security information of specified handle from file system + /// + /// Handle to get file security information + /// Result + private CommonObjectSecurity ReceiveFileSystemSecurityInformation(out IntPtr sidHandle) + { + nint zeroHandle = new( ); + nint pSecurityDescriptor = new( ); + + try + { + uint namedSecInfoResult = Win32SafeNativeMethods.GetNamedSecurityInfo( PathInfo.FullNameUnc, Win32SecurityObjectType.SeFileObject, + Win32FileSystemEntrySecurityInformation.OwnerSecurityInformation | Win32FileSystemEntrySecurityInformation.DaclSecurityInformation, + out sidHandle, out zeroHandle, out zeroHandle, out zeroHandle, out pSecurityDescriptor ); + int win32Error = Marshal.GetLastWin32Error( ); + // Cancel if call failed + + if (namedSecInfoResult != 0) + { + InternalQuickIOCommon.NativeExceptionMapping(PathInfo.FullName, win32Error); + } + + uint securityDescriptorLength = Win32SafeNativeMethods.GetSecurityDescriptorLength( pSecurityDescriptor ); + byte[] securityDescriptorDataArray = new byte[ securityDescriptorLength ]; + Marshal.Copy(pSecurityDescriptor, securityDescriptorDataArray, 0, (int)securityDescriptorLength); + + CommonObjectSecurity securityInfo; + if (InternalHelpers.ContainsFileAttribute(PathInfo.Attributes, FileAttributes.Directory)) + { + securityInfo = new DirectorySecurity(); + securityInfo.SetSecurityDescriptorBinaryForm(securityDescriptorDataArray); + } + else + { + securityInfo = new FileSecurity(); + securityInfo.SetSecurityDescriptorBinaryForm(securityDescriptorDataArray); + } + + return securityInfo; + } + finally + { + _ = Win32SafeNativeMethods.LocalFree(zeroHandle); + _ = Win32SafeNativeMethods.LocalFree(pSecurityDescriptor); + } + } + + /// + /// File System Security Information + /// + public CommonObjectSecurity FileSystemSecurityInformation { get; private set; } +} + diff --git a/src/QuickIO/QuickIOFile_Append.cs b/src/QuickIO/QuickIOFile_Append.cs new file mode 100644 index 0000000..d17f5ee --- /dev/null +++ b/src/QuickIO/QuickIOFile_Append.cs @@ -0,0 +1,117 @@ +using System.Text; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIOFile +{ + /// + /// Appends lines to a file. + /// If the file does not exist, it creates the file. + /// Uses UTF-8 Encoding. + /// + /// The file to append the lines to. The file is created if it doesn't exist. + /// The lines to append. + /// http://msdn.microsoft.com/en-us/library/dd383691(v=vs.110).aspx + public static void AppendAllLines(string path, IEnumerable contents) + { + AppendAllLines(new QuickIOPathInfo(path), contents, Encoding.UTF8); + } + + /// + /// Appends lines to a file. + /// If the file does not exist, it creates the file. + /// Uses UTF-8 Encoding. + /// + /// The file to append the lines to. The file is created if it doesn't exist. + /// The lines to append. + /// http://msdn.microsoft.com/en-us/library/dd383691(v=vs.110).aspx + public static void AppendAllLines(QuickIOPathInfo pathInfo, IEnumerable contents) + { + AppendAllLines(pathInfo, contents, QuickIOSystemRules.UTF8EncodingNoEmit); + } + + /// + /// Appends lines by using the specified encoding. + /// If the file does not exist, it creates the file. + /// + /// The file to append the lines to. The file is created if it doesn't exist. + /// The lines to append. + /// The character encoding. + /// http://msdn.microsoft.com/en-us/library/dd383356(v=vs.110).aspx + public static void AppendAllLines(string path, IEnumerable contents, Encoding encoding) + { + AppendAllLines(new QuickIOPathInfo(path), contents, encoding); + } + + /// + /// Appends lines by using the specified encoding. + /// If the file does not exist, it creates the file. + /// + /// The file to append the lines to. The file is created if it doesn't exist. + /// The lines to append. + /// The character encoding. + /// http://msdn.microsoft.com/en-us/library/dd383356(v=vs.110).aspx + public static void AppendAllLines(QuickIOPathInfo pathInfo, IEnumerable contents, Encoding encoding) + { + FileStream fileStream = OpenAppendFileStream( pathInfo, FileAccess.Write, FileMode.OpenOrCreate, FileShare.Write ); + using StreamWriter streamWriter = new(fileStream, encoding); + foreach (string line in contents) + { + streamWriter.WriteLine(line); + } + } + + /// + /// Appends the specified string. + /// If the file does not exist, it creates the file. + /// Uses UTF-8 Encoding. + /// + /// The file to append the specified string to. + /// The string to append to the file. + /// http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx + public static void AppendAllText(string path, string contents) + { + AppendAllText(new QuickIOPathInfo(path), contents, Encoding.UTF8); + } + + /// + /// Appends the specified string. + /// If the file does not exist, it creates the file. + /// Uses UTF-8 Encoding. + /// + /// The file to append the specified string to. + /// The string to append to the file. + /// http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx + public static void AppendAllText(QuickIOPathInfo pathInfo, string contents) + { + AppendAllText(pathInfo, contents, Encoding.UTF8); + } + + /// + /// Appends the specified string. + /// If the file does not exist, it creates the file. + /// + /// The file to append the specified string to. + /// The string to append to the file. + /// The character encoding. + /// http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx + public static void AppendAllText(string path, string contents, Encoding encoding) + { + AppendAllText(new QuickIOPathInfo(path), contents, encoding); + } + + /// + /// Appends the specified string. + /// If the file does not exist, it creates the file. + /// + /// The file to append the specified string to. + /// The string to append to the file. + /// The character encoding. + /// http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx + public static void AppendAllText(QuickIOPathInfo pathInfo, string contents, Encoding encoding) + { + using FileStream fileStream = OpenAppendFileStream(pathInfo, FileAccess.Write, FileMode.OpenOrCreate, FileShare.Write); + byte[] bytes = encoding.GetBytes( contents ); + fileStream.Write(bytes, 0, bytes.Length); + } +} diff --git a/src/QuickIO/QuickIOFile_Attributes.cs b/src/QuickIO/QuickIOFile_Attributes.cs new file mode 100644 index 0000000..3fe0f04 --- /dev/null +++ b/src/QuickIO/QuickIOFile_Attributes.cs @@ -0,0 +1,135 @@ +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIOFile +{ + /// + /// Gets the of the directory or file. + /// + /// The path to the directory or file. + /// New attributes to set. + /// The of the directory or file. + public static void SetAttributes(string path, FileAttributes attributes) + { + SetAttributes(new QuickIOPathInfo(path), attributes); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// New attributes to set. + /// The of the directory or file. + public static void SetAttributes(QuickIOPathInfo info, FileAttributes attributes) + { + InternalQuickIO.SetAttributes(info, attributes); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// New attributes to set. + /// The of the directory or file. + public static void SetAttributes(QuickIOFileInfo info, FileAttributes attributes) + { + InternalQuickIO.SetAttributes(info.PathInfo, attributes); + } + + /// + /// Gets the of the directory or file. + /// + /// The path to the directory or file. + /// The of the directory or file. + public static FileAttributes GetAttributes(string path) + { + return GetAttributes(new QuickIOPathInfo(path)); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// The of the directory or file. + public static FileAttributes GetAttributes(QuickIOPathInfo info) + { + return InternalQuickIO.GetAttributes(info); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// The of the directory or file. + public static FileAttributes GetAttributes(QuickIOFileInfo info) + { + return InternalQuickIO.GetAttributes(info.PathInfo); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static bool RemoveAttribute(string path, FileAttributes attribute) + { + return RemoveAttribute(new QuickIOPathInfo(path), attribute); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static bool RemoveAttribute(QuickIOPathInfo info, FileAttributes attribute) + { + return InternalQuickIO.RemoveAttribute(info, attribute); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static bool RemoveAttribute(QuickIOFileInfo info, FileAttributes attribute) + { + return InternalQuickIO.RemoveAttribute(info.PathInfo, attribute); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static bool AddAttribute(string path, FileAttributes attribute) + { + return AddAttribute(new QuickIOPathInfo(path), attribute); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static bool AddAttribute(QuickIOPathInfo info, FileAttributes attribute) + { + return InternalQuickIO.AddAttribute(info, attribute); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static bool AddAttribute(QuickIOFileInfo info, FileAttributes attribute) + { + return InternalQuickIO.AddAttribute(info.PathInfo, attribute); + } +} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.Attributes.tt b/src/QuickIO/QuickIOFile_Attributes.tt similarity index 50% rename from src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.Attributes.tt rename to src/QuickIO/QuickIOFile_Attributes.tt index c1cfcfb..cfa51eb 100644 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.Attributes.tt +++ b/src/QuickIO/QuickIOFile_Attributes.tt @@ -1,6 +1,6 @@ <#@ template language="C#" hostspecific="true" #> -<#@ include file="..\Templates\SaveOutput.tt" #> -<#@ include file="..\Templates\StaticAttributeMethods.tt" #> +<#@ include file=".\CodeTemplates\SaveOutput.tt" #> +<#@ include file=".\CodeTemplates\StaticAttributeMethods.tt" #> <#@ output extension=".cs" #> <# Generate("QuickIOFile"); diff --git a/src/QuickIO/QuickIOFile_Attributes_Async.cs b/src/QuickIO/QuickIOFile_Attributes_Async.cs new file mode 100644 index 0000000..056c379 --- /dev/null +++ b/src/QuickIO/QuickIOFile_Attributes_Async.cs @@ -0,0 +1,135 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIOFile +{ + /// + /// Gets the of the directory or file. + /// + /// The path to the directory or file. + /// New attributes to set. + /// The of the directory or file. + public static Task SetAttributesAsync(string path, FileAttributes attributes) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetAttributes(path, attributes)); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// New attributes to set. + /// The of the directory or file. + public static Task SetAttributesAsync(QuickIOPathInfo info, FileAttributes attributes) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetAttributes(info, attributes)); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// New attributes to set. + /// The of the directory or file. + public static Task SetAttributesAsync(QuickIOFileInfo info, FileAttributes attributes) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetAttributes(info.PathInfo, attributes)); + } + + /// + /// Gets the of the directory or file. + /// + /// The path to the directory or file. + /// The of the directory or file. + public static Task GetAttributesAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetAttributes(path)); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// The of the directory or file. + public static Task GetAttributesAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetAttributes(info)); + } + + /// + /// Gets the of the directory or file. + /// + /// A directory or file. + /// The of the directory or file. + public static Task GetAttributesAsync(QuickIOFileInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetAttributes(info)); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static Task RemoveAttributeAsync(string path, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.RemoveAttribute(path, attribute)); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static Task RemoveAttributeAsync(QuickIOPathInfo info, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.RemoveAttribute(info, attribute)); + } + + /// + /// Removes the specified attribute from file or directory + /// + /// A directory or file. + /// Attribute to remove + /// true if removed. false if not exists in attributes + public static Task RemoveAttributeAsync(QuickIOFileInfo info, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.RemoveAttribute(info, attribute)); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static Task AddAttributeAsync(string path, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.AddAttribute(path, attribute)); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static Task AddAttributeAsync(QuickIOPathInfo info, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.AddAttribute(info, attribute)); + } + + /// + /// Adds the specified attribute to file or directory + /// + /// A directory or file. + /// Attribute to add + /// true if added. false if already exists in attributes + public static Task AddAttributeAsync(QuickIOFileInfo info, FileAttributes attribute) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.AddAttribute(info, attribute)); + } +} diff --git a/src/QuickIO/QuickIOFile_Attributes_Async.tt b/src/QuickIO/QuickIOFile_Attributes_Async.tt new file mode 100644 index 0000000..ed0802c --- /dev/null +++ b/src/QuickIO/QuickIOFile_Attributes_Async.tt @@ -0,0 +1,7 @@ +<#@ template language="C#" hostspecific="true" #> +<#@ include file=".\CodeTemplates\SaveOutput.tt" #> +<#@ include file=".\CodeTemplates\StaticAttributeMethods_Async.tt" #> +<#@ output extension=".cs" #> +<# + Generate("QuickIOFile"); +#> \ No newline at end of file diff --git a/src/QuickIO/QuickIOFile_Create.cs b/src/QuickIO/QuickIOFile_Create.cs new file mode 100644 index 0000000..731f5cf --- /dev/null +++ b/src/QuickIO/QuickIOFile_Create.cs @@ -0,0 +1,84 @@ +using System.Text; +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + + +public static partial class QuickIOFile +{ + /// + /// Creates a new file. + /// + /// The path to the file. + /// - default + /// - default + /// - default + /// - default 0 (none) + /// The specified path already exists. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + public static void Create(string fullName, FileAccess fileAccess = FileAccess.Write, FileShare fileShare = FileShare.None, FileMode fileMode = FileMode.Create, FileAttributes fileAttributes = 0) + { + Create(new QuickIOPathInfo(fullName), fileAccess, fileShare, fileMode, fileAttributes); + } + + /// + /// Creates a new file. + /// + /// The path to the file. + /// - default + /// - default + /// - default + /// - default 0 (none) + /// The specified path already exists. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + public static void Create(QuickIOPathInfo pathInfo, FileAccess fileAccess = FileAccess.Write, FileShare fileShare = FileShare.None, FileMode fileMode = FileMode.Create, FileAttributes fileAttributes = 0) + { + InternalQuickIO.CreateFile(pathInfo, fileAccess, fileShare, fileMode, fileAttributes); + } + + /// + /// Creates or overwrites the specified file. + /// + /// The name of the file. + /// The number of bytes buffered for reads and writes to the file. + /// A with the specified buffer size that provides read/write access to the file specified in path. + /// http://msdn.microsoft.com/en-us/library/981h90e5(v=vs.110).aspx + public static FileStream Create(string path, int bufferSize) + { + return Create(new QuickIOPathInfo(path), bufferSize); + } + + /// + /// Creates or overwrites the specified file. + /// + /// The name of the file. + /// The number of bytes buffered for reads and writes to the file. + /// A with the specified buffer size that provides read/write access to the file specified in path. + /// http://msdn.microsoft.com/en-us/library/981h90e5(v=vs.110).aspx + public static FileStream Create(QuickIOPathInfo pathInfo, int bufferSize) + { + return OpenFileStream(pathInfo, FileAccess.ReadWrite, FileMode.Create, FileShare.None, bufferSize); + } + + /// + /// Creates or opens a file for writing UTF-8 encoded text. + /// + /// The file. + /// A that writes to the specified file using UTF-8 encoding. + /// http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx + public static StreamWriter CreateText(string path) + { + return CreateText(new QuickIOPathInfo(path)); + } + + /// + /// Creates or opens a file for writing UTF-8 encoded text. + /// + /// The file. + /// A that writes to the specified file using UTF-8 encoding. + /// http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx + public static StreamWriter CreateText(QuickIOPathInfo pathInfo) + { + return new StreamWriter(OpenFileStream(pathInfo, FileAccess.ReadWrite, FileMode.Create, FileShare.None), Encoding.UTF8); + } +} diff --git a/src/QuickIO/QuickIOFile_FileTime.cs b/src/QuickIO/QuickIOFile_FileTime.cs new file mode 100644 index 0000000..bb89e21 --- /dev/null +++ b/src/QuickIO/QuickIOFile_FileTime.cs @@ -0,0 +1,460 @@ +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIOFile +{ + /// + /// Returns the creation time of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTime(String path) + { + return GetCreationTimeUtc(path).ToLocalTime(); + } + /// + /// Returns the creation time of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTime(QuickIOPathInfo info) + { + return GetCreationTimeUtc(info).ToLocalTime(); + } + /// + /// Returns the creation time of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTime(QuickIOFileInfo info) + { + return GetCreationTimeUtc(info.PathInfo).ToLocalTime(); + } + + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTimeUtc(String path) + { + return GetCreationTimeUtc(new QuickIOPathInfo(path)); + } + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetCreationTimeUtc(QuickIOPathInfo info) + { + return info.FindData.GetCreationTimeUtc(); + } + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime? GetCreationTimeUtc(QuickIOFileInfo info) + { + return info.FindData?.GetCreationTimeUtc(); + } + + /// + /// Returns the time of last access of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTime(String path) + { + return GetLastAccessTimeUtc(path).ToLocalTime(); + } + /// + /// Returns the time of last access of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTime(QuickIOPathInfo info) + { + return GetLastAccessTimeUtc(info).ToLocalTime(); + } + /// + /// Returns the time of last access of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTime(QuickIOFileInfo info) + { + return GetLastAccessTimeUtc(info.PathInfo).ToLocalTime(); + } + + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTimeUtc(String path) + { + return GetLastAccessTimeUtc(new QuickIOPathInfo(path)); + } + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastAccessTimeUtc(QuickIOPathInfo info) + { + return info.FindData.GetLastAccessTimeUtc(); + } + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime? GetLastAccessTimeUtc(QuickIOFileInfo info) + { + return info.FindData?.GetLastAccessTimeUtc(); + } + + /// + /// Returns the time of the file or directory was last written + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTime(String path) + { + return GetLastWriteTimeUtc(path).ToLocalTime(); + } + /// + /// Returns the time of the file or directory was last written + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTime(QuickIOPathInfo info) + { + return GetLastWriteTimeUtc(info).ToLocalTime(); + } + /// + /// Returns the time of the file or directory was last written + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTime(QuickIOFileInfo info) + { + return GetLastWriteTimeUtc(info.PathInfo).ToLocalTime(); + } + + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTimeUtc(String path) + { + return GetLastWriteTimeUtc(new QuickIOPathInfo(path)); + } + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime GetLastWriteTimeUtc(QuickIOPathInfo info) + { + return info.FindData.GetLastWriteTimeUtc(); + } + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static DateTime? GetLastWriteTimeUtc(QuickIOFileInfo info) + { + return info.FindData?.GetLastWriteTimeUtc(); + } + + /// + /// Sets the time the file was created. + /// + /// Affected file or directory + /// The time that is to be used + /// The time that is to be used + /// The time that is to be used + public static void SetAllFileTimes(String path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) + { + SetAllFileTimesUtc(path, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime()); + } + /// + /// Sets the time the file was created. + /// + /// Affected file or directory + /// The time that is to be used + /// The time that is to be used + /// The time that is to be used + public static void SetAllFileTimes(QuickIOPathInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) + { + SetAllFileTimesUtc(info, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime()); + } + /// + /// Sets the time the file was created. + /// + /// Affected file or directory + /// The time that is to be used + /// The time that is to be used + /// The time that is to be used + public static void SetAllFileTimes(QuickIOFileInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) + { + SetAllFileTimesUtc(info, creationTime.ToUniversalTime(), lastAccessTime.ToUniversalTime(), lastWriteTime.ToUniversalTime()); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static void SetAllFileTimesUtc(String path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + InternalQuickIO.SetAllFileTimes(new QuickIOPathInfo(path), creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static void SetAllFileTimesUtc(QuickIOPathInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + InternalQuickIO.SetAllFileTimes(info, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static void SetAllFileTimesUtc(QuickIOFileInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + InternalQuickIO.SetAllFileTimes(info.PathInfo, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc); + } + + /// + /// Defines the time at which the file or directory was created + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetCreationTime(String path, DateTime creationTime) + { + SetCreationTimeUtc(path, creationTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was created + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetCreationTime(QuickIOPathInfo info, DateTime creationTime) + { + SetCreationTimeUtc(info, creationTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was created + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetCreationTime(QuickIOFileInfo info, DateTime creationTime) + { + SetCreationTimeUtc(info, creationTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static void SetCreationTimeUtc(String path, DateTime creationTimeUtc) + { + InternalQuickIO.SetCreationTimeUtc(new QuickIOPathInfo(path), creationTimeUtc); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static void SetCreationTimeUtc(QuickIOPathInfo info, DateTime creationTimeUtc) + { + InternalQuickIO.SetCreationTimeUtc(info, creationTimeUtc); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static void SetCreationTimeUtc(QuickIOFileInfo info, DateTime creationTimeUtc) + { + InternalQuickIO.SetCreationTimeUtc(info.PathInfo, creationTimeUtc); + } + + /// + /// Defines the time at which the file or directory was last accessed + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetLastAccessTime(String path, DateTime lastAccessTime) + { + SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was last accessed + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx + public static void SetLastAccessTime(QuickIOPathInfo info, DateTime lastAccessTime) + { + SetLastAccessTimeUtc(info, lastAccessTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was last accessed + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx + public static void SetLastAccessTime(QuickIOFileInfo info, DateTime lastAccessTime) + { + SetLastAccessTimeUtc(info, lastAccessTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc) + { + InternalQuickIO.SetLastAccessTimeUtc(new QuickIOPathInfo(path), lastAccessTimeUtc); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static void SetLastAccessTimeUtc(QuickIOPathInfo info, DateTime lastAccessTimeUtc) + { + InternalQuickIO.SetLastAccessTimeUtc(info, lastAccessTimeUtc); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static void SetLastAccessTimeUtc(QuickIOFileInfo info, DateTime lastAccessTimeUtc) + { + InternalQuickIO.SetLastAccessTimeUtc(info.PathInfo, lastAccessTimeUtc); + } + + /// + /// Defines the time at which the file or directory was last written + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static void SetLastWriteTime(String path, DateTime lastWriteTime) + { + SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was last written + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx + public static void SetLastWriteTime(QuickIOPathInfo info, DateTime lastWriteTime) + { + SetLastWriteTimeUtc(info, lastWriteTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was last written + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx + public static void SetLastWriteTime(QuickIOFileInfo info, DateTime lastWriteTime) + { + SetLastWriteTimeUtc(info, lastWriteTime.ToUniversalTime()); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc) + { + InternalQuickIO.SetLastWriteTimeUtc(new QuickIOPathInfo(path), lastWriteTimeUtc); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static void SetLastWriteTimeUtc(QuickIOPathInfo info, DateTime lastWriteTimeUtc) + { + InternalQuickIO.SetLastWriteTimeUtc(info, lastWriteTimeUtc); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static void SetLastWriteTimeUtc(QuickIOFileInfo info, DateTime lastWriteTimeUtc) + { + InternalQuickIO.SetLastWriteTimeUtc(info.PathInfo, lastWriteTimeUtc); + } +} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.Root.tt b/src/QuickIO/QuickIOFile_FileTime.tt similarity index 50% rename from src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.Root.tt rename to src/QuickIO/QuickIOFile_FileTime.tt index 3c56ec8..eb6e1eb 100644 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.Root.tt +++ b/src/QuickIO/QuickIOFile_FileTime.tt @@ -1,6 +1,6 @@ <#@ template language="C#" hostspecific="true" #> -<#@ include file="..\Templates\SaveOutput.tt" #> -<#@ include file="..\Templates\StaticRootMethods.tt" #> +<#@ include file=".\CodeTemplates\SaveOutput.tt" #> +<#@ include file=".\CodeTemplates\StaticFileTimeMethods.tt" #> <#@ output extension=".cs" #> <# Generate("QuickIOFile"); diff --git a/src/QuickIO/QuickIOFile_FileTime_Async.cs b/src/QuickIO/QuickIOFile_FileTime_Async.cs new file mode 100644 index 0000000..9c7d121 --- /dev/null +++ b/src/QuickIO/QuickIOFile_FileTime_Async.cs @@ -0,0 +1,460 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIOFile +{ + /// + /// Returns the creation time of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetCreationTime(path)); + } + /// + /// Returns the creation time of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetCreationTime(info)); + } + /// + /// Returns the creation time of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeAsync(QuickIOFileInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetCreationTime(info)); + } + + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeUtcAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetCreationTimeUtc(path)); + } + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeUtcAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetCreationTimeUtc(info)); + } + /// + /// Returns the creation time of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetCreationTimeUtcAsync(QuickIOFileInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetCreationTimeUtc(info)); + } + + /// + /// Returns the time of last access of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetLastAccessTime(path)); + } + /// + /// Returns the time of last access of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetLastAccessTime(info)); + } + /// + /// Returns the time of last access of the file or directory + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeAsync(QuickIOFileInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetLastAccessTime(info)); + } + + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeUtcAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetLastAccessTimeUtc(path)); + } + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeUtcAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetLastAccessTimeUtc(info)); + } + /// + /// Returns the time of last access of the file or directory (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastAccessTimeUtcAsync(QuickIOFileInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetLastAccessTimeUtc(info)); + } + + /// + /// Returns the time of the file or directory was last written + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetLastAccessTimeUtc(path)); + } + /// + /// Returns the time of the file or directory was last written + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetLastAccessTimeUtc(info)); + } + /// + /// Returns the time of the file or directory was last written + /// + /// Affected file or directory + /// A structure. + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeAsync(QuickIOFileInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetLastAccessTimeUtc(info)); + } + + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeUtcAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetLastWriteTimeUtc(path)); + } + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeUtcAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetLastWriteTimeUtc(info)); + } + /// + /// Returns the time of the file or directory was last written (UTC) + /// + /// Affected file or directory + /// A structure. (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx + /// No entry found for passed path + public static Task GetLastWriteTimeUtcAsync(QuickIOFileInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetLastWriteTimeUtc(info)); + } + + /// + /// Sets the time the file was created. + /// + /// Affected file or directory + /// The time that is to be used + /// The time that is to be used + /// The time that is to be used + public static Task SetAllFileTimesAsync(string path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetAllFileTimes(path, creationTime, lastAccessTime, lastWriteTime)); + } + /// + /// Sets the time the file was created. + /// + /// Affected file or directory + /// The time that is to be used + /// The time that is to be used + /// The time that is to be used + public static Task SetAllFileTimesAsync(QuickIOPathInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetAllFileTimes(info, creationTime, lastAccessTime, lastWriteTime)); + } + /// + /// Sets the time the file was created. + /// + /// Affected file or directory + /// The time that is to be used + /// The time that is to be used + /// The time that is to be used + public static Task SetAllFileTimesAsync(QuickIOFileInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetAllFileTimes(info, creationTime, lastAccessTime, lastWriteTime)); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static Task SetAllFileTimesUtcAsync(string path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetAllFileTimesUtc(path, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc)); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static Task SetAllFileTimesUtcAsync(QuickIOPathInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetAllFileTimesUtc(info, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc)); + } + /// + /// Sets the dates and times of given directory or file. + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + /// The time that is to be used (UTC) + public static Task SetAllFileTimesUtcAsync(QuickIOFileInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetAllFileTimesUtc(info, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc)); + } + + /// + /// Defines the time at which the file or directory was created + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetCreationTimeAsync(string path, DateTime creationTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetCreationTime(path, creationTime)); + } + /// + /// Defines the time at which the file or directory was created + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetCreationTimeAsync(QuickIOPathInfo info, DateTime creationTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetCreationTime(info, creationTime)); + } + /// + /// Defines the time at which the file or directory was created + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetCreationTimeAsync(QuickIOFileInfo info, DateTime creationTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetCreationTime(info, creationTime)); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static Task SetCreationTimeUtcAsync(string path, DateTime creationTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetCreationTimeUtc(path, creationTimeUtc)); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static Task SetCreationTimeUtcAsync(QuickIOPathInfo info, DateTime creationTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetCreationTimeUtc(info, creationTimeUtc)); + } + /// + /// Defines the time at which the file or directory was created (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx + public static Task SetCreationTimeUtcAsync(QuickIOFileInfo info, DateTime creationTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetCreationTimeUtc(info, creationTimeUtc)); + } + + /// + /// Defines the time at which the file or directory was last accessed + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetLastAccessTimeAsync(string path, DateTime lastAccessTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetLastAccessTime(path, lastAccessTime)); + } + /// + /// Defines the time at which the file or directory was last accessed + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx + public static Task SetLastAccessTimeAsync(QuickIOPathInfo info, DateTime lastAccessTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetLastAccessTime(info, lastAccessTime)); + } + /// + /// Defines the time at which the file or directory was last accessed + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx + public static Task SetLastAccessTimeAsync(QuickIOFileInfo info, DateTime lastAccessTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetLastAccessTime(info, lastAccessTime)); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static Task SetLastAccessTimeUtcAsync(string path, DateTime lastAccessTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetLastAccessTimeUtc(path, lastAccessTimeUtc)); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static Task SetLastAccessTimeUtcAsync(QuickIOPathInfo info, DateTime lastAccessTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetLastAccessTimeUtc(info, lastAccessTimeUtc)); + } + /// + /// Defines the time at which the file or directory was last accessed (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx + public static Task SetLastAccessTimeUtcAsync(QuickIOFileInfo info, DateTime lastAccessTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetLastAccessTimeUtc(info, lastAccessTimeUtc)); + } + + /// + /// Defines the time at which the file or directory was last written + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx + public static Task SetLastWriteTimeAsync(string path, DateTime lastWriteTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetLastWriteTime(path, lastWriteTime)); + } + /// + /// Defines the time at which the file or directory was last written + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx + public static Task SetLastWriteTimeAsync(QuickIOPathInfo info, DateTime lastWriteTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetLastWriteTime(info, lastWriteTime)); + } + /// + /// Defines the time at which the file or directory was last written + /// + /// Affected file or directory + /// The time that is to be used + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx + public static Task SetLastWriteTimeAsync(QuickIOFileInfo info, DateTime lastWriteTime) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetLastWriteTime(info, lastWriteTime)); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static Task SetLastWriteTimeUtcAsync(string path, DateTime lastWriteTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetLastWriteTimeUtc(path, lastWriteTimeUtc)); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static Task SetLastWriteTimeUtcAsync(QuickIOPathInfo info, DateTime lastWriteTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetLastWriteTimeUtc(info, lastWriteTimeUtc)); + } + /// + /// Defines the time at which the file or directory was last written (UTC) + /// + /// Affected file or directory + /// The time that is to be used (UTC) + /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx + public static Task SetLastWriteTimeUtcAsync(QuickIOFileInfo info, DateTime lastWriteTimeUtc) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => QuickIOFile.SetLastWriteTimeUtc(info, lastWriteTimeUtc)); + } +} diff --git a/src/QuickIO/QuickIOFile_FileTime_Async.tt b/src/QuickIO/QuickIOFile_FileTime_Async.tt new file mode 100644 index 0000000..d81c4fe --- /dev/null +++ b/src/QuickIO/QuickIOFile_FileTime_Async.tt @@ -0,0 +1,7 @@ +<#@ template language="C#" hostspecific="true" #> +<#@ include file=".\CodeTemplates\SaveOutput.tt" #> +<#@ include file=".\CodeTemplates\StaticFileTimeMethods_Async.tt" #> +<#@ output extension=".cs" #> +<# + Generate("QuickIOFile"); +#> \ No newline at end of file diff --git a/src/QuickIO/QuickIOFile_Hash.cs b/src/QuickIO/QuickIOFile_Hash.cs new file mode 100644 index 0000000..940925d --- /dev/null +++ b/src/QuickIO/QuickIOFile_Hash.cs @@ -0,0 +1,147 @@ +using System.Security.Cryptography; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIOFile +{ + /// + /// File content hash calculation + /// + public static QuickIOHashResult CalculateHash(QuickIOPathInfo pathInfo, QuickIOHashImplementationType hashImplementationType) + { + switch (hashImplementationType) + { + case QuickIOHashImplementationType.SHA1: + return CalculateSha1Hash(pathInfo); + + case QuickIOHashImplementationType.SHA256: + return CalculateSha256Hash(pathInfo); + + case QuickIOHashImplementationType.SHA384: + return CalculateSha384Hash(pathInfo); + + case QuickIOHashImplementationType.SHA512: + return CalculateSha512Hash(pathInfo); + + case QuickIOHashImplementationType.MD5: + return CalculateMD5Hash(pathInfo); + + default: + throw new NotImplementedException("Type " + hashImplementationType + " not implemented."); + } + } + + /// + /// File content hash calculation + /// + /// + /// + /// // Implementation of + /// public static QuickIOHashResult CalculateSha256Hash( QuickIOPathInfo pathInfo ) + /// { + /// using ( var fs = OpenRead( pathInfo ) ) + /// using ( var hashAlgorithm = SHA256.Create( ) ) + /// { + /// return CalculateHash( hashAlgorithm, fs ); + /// } + /// } + /// + /// + /// + public static QuickIOHashResult CalculateHash(HashAlgorithm hashAlgorithm, Stream stream) + { + return new QuickIOHashResult(hashAlgorithm.ComputeHash(stream)); + } + + /// + /// File content hash calculation using SHA1 + /// + /// + /// + /// + /// // Show human readable hash + /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha1Hash( "C:\temp\image.bin" ); + /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8, "x2" ); + /// + /// + public static QuickIOHashResult CalculateSha1Hash(QuickIOPathInfo pathInfo) + { + using FileStream fs = OpenRead(pathInfo); + using SHA1 hashAlgorithm = SHA1.Create(); + return CalculateHash(hashAlgorithm, fs); + } + + /// + /// File content hash calculation using SHA256 + /// + /// + /// Not compatible with FIPS
http://msdn.microsoft.com/de-de/library/hydyw22a(v=vs.110).aspx
+ /// + /// + /// // Show human readable hash + /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" ); + /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8, "x2" ); + /// + /// + public static QuickIOHashResult CalculateSha256Hash(QuickIOPathInfo pathInfo) + { + using FileStream fs = OpenRead(pathInfo); + using SHA256 hashAlgorithm = SHA256.Create(); + return CalculateHash(hashAlgorithm, fs); + } + + /// + /// File content hash calculation using SHA384 + /// + /// + /// + /// + /// // Show human readable hash + /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha384Hash( "C:\temp\image.bin" ); + /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8, "x2" ); + /// + /// + public static QuickIOHashResult CalculateSha384Hash(QuickIOPathInfo pathInfo) + { + using FileStream fs = OpenRead(pathInfo); + using SHA384 hashAlgorithm = SHA384.Create(); + return CalculateHash(hashAlgorithm, fs); + } + + /// + /// File content hash calculation using SHA512 + /// + /// + /// Not compatible with FIPS
http://msdn.microsoft.com/de-de/library/hydyw22a(v=vs.110).aspx
+ /// + /// + /// // Show human readable hash + /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha512Hash( "C:\temp\image.bin" ); + /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8, "x2" ); + /// + /// + public static QuickIOHashResult CalculateSha512Hash(QuickIOPathInfo pathInfo) + { + using FileStream fs = OpenRead(pathInfo); + using SHA512 hashAlgorithm = SHA512.Create(); + return CalculateHash(hashAlgorithm, fs); + } + + /// + /// File content hash calculation using MD5 + /// + /// + /// + /// + /// // Show human readable hash + /// QuickIOHashResult hashResult = QuickIOFile.CalculateMD5Hash( "C:\temp\image.bin" ); + /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8, "x2" ); + /// + /// + public static QuickIOHashResult CalculateMD5Hash(QuickIOPathInfo pathInfo) + { + using FileStream fs = OpenRead(pathInfo); + using MD5 hashAlgorithm = MD5.Create(); + return CalculateHash(hashAlgorithm, fs); + } +} diff --git a/src/QuickIO/QuickIOFile_Open.cs b/src/QuickIO/QuickIOFile_Open.cs new file mode 100644 index 0000000..c80cfb8 --- /dev/null +++ b/src/QuickIO/QuickIOFile_Open.cs @@ -0,0 +1,207 @@ +using System.Runtime.InteropServices; +using System.Text; +using Microsoft.Win32.SafeHandles; +using SchwabenCode.QuickIO.Internal; +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIOFile +{ + /// + /// Opens a + /// + /// The file to open. + /// + /// A with read and write access and not shared. + /// http://msdn.microsoft.com/en-us/library/b9skfh7s(v=vs.110).aspx + public static FileStream Open(string path, FileMode mode = FileMode.Open) + { + return Open(new QuickIOPathInfo(path), mode); + } + + /// + /// Opens a + /// + /// The file to open. + /// + /// A with read and write access and not shared. + /// http://msdn.microsoft.com/en-us/library/b9skfh7s(v=vs.110).aspx + public static FileStream Open(QuickIOPathInfo info, FileMode mode = FileMode.Open) + { + return OpenFileStream(info, FileAccess.ReadWrite, mode, FileShare.None); + } + + + /// + /// Opens a + /// + /// The file to open. + /// + /// + /// An unshared + /// http://msdn.microsoft.com/en-us/library/s67691sb(v=vs.110).aspx + public static FileStream Open(string path, FileMode mode, FileAccess access) + { + return Open(new QuickIOPathInfo(path), mode, access); + } + + /// + /// Opens a + /// + /// The file to open. + /// + /// + /// An unshared + /// http://msdn.microsoft.com/en-us/library/s67691sb(v=vs.110).aspx + public static FileStream Open(QuickIOPathInfo pathInfo, FileMode mode, FileAccess access) + { + return OpenFileStream(pathInfo, access, mode, FileShare.None); + } + + /// + /// Opens a + /// + private static FileStream OpenFileStream(QuickIOPathInfo pathInfo, FileAccess fileAccess, FileMode fileOption = FileMode.Open, FileShare shareMode = FileShare.Read, int buffer = 0) + { + SafeFileHandle fileHandle = Win32SafeNativeMethods.CreateFile( pathInfo.FullNameUnc, fileAccess, shareMode, IntPtr.Zero, fileOption, 0, IntPtr.Zero ); + int win32Error = Marshal.GetLastWin32Error( ); + if (fileHandle.IsInvalid) + { + InternalQuickIOCommon.NativeExceptionMapping(pathInfo.FullName, win32Error); // Throws an exception + } + + return buffer > 0 ? new FileStream(fileHandle, fileAccess, buffer) : new FileStream(fileHandle, fileAccess); + } + + /// + /// Opens a + /// + private static FileStream OpenAppendFileStream(QuickIOPathInfo pathInfo, FileAccess fileAccess, FileMode fileOption = FileMode.Open, FileShare shareMode = FileShare.Read, int buffer = 0) + { + Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle = Win32SafeNativeMethods.CreateFileForAppend( pathInfo.FullNameUnc, 0x0004 /* Internal Win Append Mode*/, shareMode, IntPtr.Zero, fileOption, 0, IntPtr.Zero ); + int win32Error = Marshal.GetLastWin32Error( ); + if (fileHandle.IsInvalid) + { + InternalQuickIOCommon.NativeExceptionMapping(pathInfo.FullName, win32Error); // Throws an exception + } + + return buffer > 0 ? new FileStream(fileHandle, fileAccess, buffer) : new FileStream(fileHandle, fileAccess); + } + + /// + /// Opens a + /// + /// The file to open. + /// + /// + /// + /// A + /// http://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx + public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share) + { + return OpenFileStream(new QuickIOPathInfo(path), access, mode, share); + } + + /// + /// Opens a + /// + /// The file to open. + /// + /// + /// + /// + /// http://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx + public static FileStream Open(QuickIOPathInfo pathInfo, FileMode mode, FileAccess access, FileShare share) + { + return OpenFileStream(pathInfo, access, mode, share); + } + + /// + /// Opens an existing file for reading. + /// + /// The file to be opened for reading. + /// A read-only on the specified path. + /// http://msdn.microsoft.com/en-us/library/system.io.file.openread(v=vs.110).aspx + public static FileStream OpenRead(string path) + { + return OpenRead(new QuickIOPathInfo(path)); + } + + /// + /// Opens an existing file for reading. + /// + /// The file to be opened for reading. + /// A read-only on the specified path. + /// http://msdn.microsoft.com/en-us/library/system.io.file.openread(v=vs.110).aspx + public static FileStream OpenRead(QuickIOPathInfo pathInfo) + { + return OpenFileStream(pathInfo, FileAccess.Read, FileMode.Open, FileShare.Read); + } + + /// + /// Opens an existing UTF-8 encoded text file for reading. + /// + /// The file to be opened for reading. + /// A . + /// http://msdn.microsoft.com/en-us/library/system.io.file.opentext(v=vs.110).aspx + public static StreamReader OpenText(string path) + { + return OpenText(new QuickIOPathInfo(path)); + } + + /// + /// Opens an existing UTF-8 encoded text file for reading. + /// + /// The file. + /// A . + /// http://msdn.microsoft.com/en-us/library/system.io.file.opentext(v=vs.110).aspx + public static StreamReader OpenText(QuickIOPathInfo pathInfo) + { + return new StreamReader(OpenFileStream(pathInfo, FileAccess.ReadWrite, FileMode.Open, FileShare.Read), Encoding.UTF8); + } + + /// + /// Opens an existing file or creates a new file for writing. + /// + /// The file. + /// An unshared with Write access. + /// http://msdn.microsoft.com/en-us/library/system.io.file.openwrite(v=vs.110).aspx + public static FileStream OpenWrite(string path) + { + return OpenWrite(new QuickIOPathInfo(path)); + } + + /// + /// Opens an existing file or creates a new file for writing. + /// + /// The file. + /// An unshared with Write access. + /// http://msdn.microsoft.com/en-us/library/system.io.file.openwrite(v=vs.110).aspx + public static FileStream OpenWrite(QuickIOPathInfo pathInfo) + { + return OpenFileStream(pathInfo, FileAccess.ReadWrite, FileMode.OpenOrCreate, FileShare.None); + } + + /// + /// Opens an existing file or creates a new file for appending. + /// + /// The file. + /// An unshared with Write access. + /// http://msdn.microsoft.com/en-us/library/system.io.file.openwrite(v=vs.110).aspx + public static FileStream OpenAppend(string path) + { + return OpenAppend(new QuickIOPathInfo(path)); + } + + /// + /// Opens an existing file or creates a new file for appending. + /// + /// The file. + /// An unshared with Write access. + /// http://msdn.microsoft.com/en-us/library/system.io.file.openwrite(v=vs.110).aspx + public static FileStream OpenAppend(QuickIOPathInfo pathInfo) + { + return OpenFileStream(pathInfo, FileAccess.ReadWrite, FileMode.Append, FileShare.None); + } +} diff --git a/src/QuickIO/QuickIOFile_Read.cs b/src/QuickIO/QuickIOFile_Read.cs new file mode 100644 index 0000000..2c58d5a --- /dev/null +++ b/src/QuickIO/QuickIOFile_Read.cs @@ -0,0 +1,126 @@ +using System.Text; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIOFile +{ + /// + /// Opens a binary file, reads the contents of the file into a byte array, and then closes the file. + /// + /// The file to open for reading. + /// A byte array containing the contents of the file. + /// http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes(v=vs.110).aspx + public static byte[] ReadAllBytes(string path) + => ReadAllBytes(new QuickIOPathInfo(path)); + + /// + /// Reads the contents of the file into a byte collection. + /// + /// The file. + /// Read buffer byte size + /// A byte collection containing the contents. + /// http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes(v=vs.110).aspx + public static byte[] ReadAllBytes(QuickIOPathInfo pathInfo, int readBuffer = 1024) + { + using FileStream readStream = OpenRead(pathInfo); + byte[] buffer = new byte[ readBuffer ]; + + using MemoryStream ms = new(); + int read; + + while ((read = readStream.Read(buffer, 0, buffer.Length)) > 0) + { + ms.Write(buffer, 0, read); + } + + return ms.ToArray(); + } + + /// + /// Reads all lines. + /// + /// The file. + /// A string collection containing all lines. + /// http://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx + public static IEnumerable ReadAllLines(string path) + => ReadAllLines(path, Encoding.UTF8); + + /// + /// Reads all lines. + /// + /// The file. + /// A string collection containing all lines. + /// http://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx + public static IEnumerable ReadAllLines(QuickIOPathInfo pathInfo) + => ReadAllLines(pathInfo, Encoding.UTF8); + + /// + /// Reads all lines with the specified encoding + /// + /// The file. + /// The encoding applied to the contents. + /// A string collection containing all lines. + /// http://msdn.microsoft.com/en-us/library/bsy4fhsa(v=vs.110).aspx + public static IEnumerable ReadAllLines(string path, Encoding encoding) + => ReadAllLines(new QuickIOPathInfo(path), encoding); + + /// + /// Reads all lines with the specified encoding + /// + /// The file. + /// The encoding applied to the contents. + /// A string collection containing all lines. + /// http://msdn.microsoft.com/en-us/library/bsy4fhsa(v=vs.110).aspx + public static IEnumerable ReadAllLines(QuickIOPathInfo pathInfo, Encoding encoding) + { + using StreamReader streamReader = new(OpenRead(pathInfo.FullNameUnc), encoding); + while (streamReader.Peek() >= 0) + { + string? line = streamReader.ReadLine(); + if (line is not null) + { + yield return line; + } + } + } + + /// + /// Reads all text. + /// + /// The file. + /// A string represents the content. + /// http://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx + public static string ReadAllText(string path) + => ReadAllText(new QuickIOPathInfo(path)); + + /// + /// Reads all text. + /// + /// The file. + /// A string represents the content. + public static string ReadAllText(QuickIOPathInfo pathInfo) + => ReadAllText(pathInfo, Encoding.UTF8); + + /// + /// Reads all text with the specified encoding. + /// + /// The file. + /// The encoding applied to the content. + /// A string represents the content. + /// http://msdn.microsoft.com/en-us/library/ms143369(v=vs.110).aspx + public static string ReadAllText(string path, Encoding encoding) + => ReadAllText(new QuickIOPathInfo(path), encoding); + + /// + /// Reads all text with the specified encoding. + /// + /// The file. + /// The encoding applied to the content. + /// A string represents the content. + /// http://msdn.microsoft.com/en-us/library/ms143369(v=vs.110).aspx + public static string ReadAllText(QuickIOPathInfo pathInfo, Encoding encoding) + { + using StreamReader streamReader = new(OpenRead(pathInfo.FullNameUnc), encoding); + return streamReader.ReadToEnd(); + } +} diff --git a/src/QuickIO/QuickIOFile_Root.cs b/src/QuickIO/QuickIOFile_Root.cs new file mode 100644 index 0000000..e18e9b0 --- /dev/null +++ b/src/QuickIO/QuickIOFile_Root.cs @@ -0,0 +1,38 @@ + +namespace SchwabenCode.QuickIO; + +public partial class QuickIOFile +{ + /// + /// Returns the root information + /// + /// The path of a file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static QuickIOPathInfo? GetDirectoryRoot(string path) + { + return GetDirectoryRoot(new QuickIOPathInfo(path)); + } + + /// + /// Returns the root information + /// + /// A file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static QuickIOPathInfo? GetDirectoryRoot(QuickIOPathInfo info) + { + return info.Root; + } + + /// + /// Returns the root information + /// + /// A file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static QuickIOPathInfo? GetDirectoryRoot(QuickIOFileInfo info) + { + return info.Root; + } +} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.FileTime.tt b/src/QuickIO/QuickIOFile_Root.tt similarity index 51% rename from src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.FileTime.tt rename to src/QuickIO/QuickIOFile_Root.tt index e50d1be..720cc73 100644 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.FileTime.tt +++ b/src/QuickIO/QuickIOFile_Root.tt @@ -1,6 +1,6 @@ <#@ template language="C#" hostspecific="true" #> -<#@ include file="..\Templates\SaveOutput.tt" #> -<#@ include file="..\Templates\StaticFileTimeMethods.tt" #> +<#@ include file=".\CodeTemplates\SaveOutput.tt" #> +<#@ include file=".\CodeTemplates\StaticRootMethods.tt" #> <#@ output extension=".cs" #> <# Generate("QuickIOFile"); diff --git a/src/QuickIO/QuickIOFile_Root_Async.cs b/src/QuickIO/QuickIOFile_Root_Async.cs new file mode 100644 index 0000000..7ea4cf1 --- /dev/null +++ b/src/QuickIO/QuickIOFile_Root_Async.cs @@ -0,0 +1,39 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIOFile +{ + /// + /// Returns the root information + /// + /// The path of a file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static Task GetDirectoryRootAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetDirectoryRoot(path)); + } + + /// + /// Returns the root information + /// + /// A file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static Task GetDirectoryRootAsync(QuickIOPathInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetDirectoryRoot(info)); + } + + /// + /// Returns the root information + /// + /// A file or directory. + /// A QuickIOPathInfo that represents the root or null if is root. + /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx + public static Task GetDirectoryRootAsync(QuickIOFileInfo info) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => QuickIOFile.GetDirectoryRoot(info)); + } +} diff --git a/src/QuickIO/QuickIOFile_Root_Async.tt b/src/QuickIO/QuickIOFile_Root_Async.tt new file mode 100644 index 0000000..56bd5b6 --- /dev/null +++ b/src/QuickIO/QuickIOFile_Root_Async.tt @@ -0,0 +1,7 @@ +<#@ template language="C#" hostspecific="true" #> +<#@ include file=".\CodeTemplates\SaveOutput.tt" #> +<#@ include file=".\CodeTemplates\StaticRootMethods_Async.tt" #> +<#@ output extension=".cs" #> +<# + Generate("QuickIOFile"); +#> \ No newline at end of file diff --git a/src/QuickIO/QuickIOFile_Write.cs b/src/QuickIO/QuickIOFile_Write.cs new file mode 100644 index 0000000..fbf7f5a --- /dev/null +++ b/src/QuickIO/QuickIOFile_Write.cs @@ -0,0 +1,164 @@ +using System.Text; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIOFile +{ + + /// + /// Writes the specified byte array. + /// If the file already exists, it is overwritten. + /// + /// The file. + /// The bytes to write. + /// http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes(v=vs.110).aspx + public static void WriteAllBytes(string path, IEnumerable bytes) + { + WriteAllBytes(new QuickIOPathInfo(path), bytes); + } + + /// + /// Writes the specified byte array. + /// If the file already exists, it is overwritten. + /// + /// The file. + /// The bytes to write. + /// http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes(v=vs.110).aspx + public static void WriteAllBytes(QuickIOPathInfo pathInfo, IEnumerable bytes) + { + WriteAllBytes(pathInfo, bytes.ToArray()); + } + + + /// + /// Writes the specified byte array. + /// If the file already exists, it is overwritten. + /// + /// The file. + /// The bytes to write. + /// http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes(v=vs.110).aspx + public static void WriteAllBytes(string path, byte[] bytes) + { + WriteAllBytes(new QuickIOPathInfo(path), bytes); + } + + /// + /// Writes the specified byte array. + /// If the file already exists, it is overwritten. + /// + /// The file. + /// The bytes to write. + /// http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes(v=vs.110).aspx + public static void WriteAllBytes(QuickIOPathInfo pathInfo, byte[] bytes) + { + using FileStream fileStream = OpenFileStream(pathInfo, FileAccess.ReadWrite, FileMode.Create, FileShare.None); + _ = fileStream.Seek(0, SeekOrigin.Begin); + fileStream.Write(bytes, 0, bytes.Length); + } + + /// + /// Writes a collection of strings. + /// Uses UTF-8 without Emitted UTF-8 identifier. + /// + /// The file. + /// The lines write to. + /// http://msdn.microsoft.com/en-us/library/dd383693(v=vs.110).aspx + public static void WriteAllLines(string path, IEnumerable contents) + { + WriteAllLines(new QuickIOPathInfo(path), contents, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + } + + /// + /// Writes a collection of strings. + /// Uses UTF-8 without Emitted UTF-8 identifier. + /// + /// The file. + /// The lines write to. + /// http://msdn.microsoft.com/en-us/library/dd383693(v=vs.110).aspx + public static void WriteAllLines(QuickIOPathInfo pathInfo, IEnumerable contents) + { + WriteAllLines(pathInfo, contents, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + } + + + /// + /// Writes a collection of strings. + /// + /// The file. + /// The lines write to. + /// The character encoding to use. + /// http://msdn.microsoft.com/en-us/library/dd383463(v=vs.110).aspx + public static void WriteAllLines(string path, IEnumerable contents, Encoding encoding) + { + WriteAllLines(new QuickIOPathInfo(path), contents, encoding); + } + + /// + /// Writes a collection of strings. + /// + /// The file. + /// The lines write to. + /// The character encoding to use. + /// http://msdn.microsoft.com/en-us/library/dd383463(v=vs.110).aspx + public static void WriteAllLines(QuickIOPathInfo pathInfo, IEnumerable contents, Encoding encoding) + { + FileStream fileStream = OpenFileStream( pathInfo, FileAccess.ReadWrite, FileMode.Create, FileShare.None ); + using StreamWriter streamWriter = new(fileStream, encoding); + foreach (string entry in contents) + { + streamWriter.WriteLine(entry); + } + } + + /// + /// Writes the specified string. + /// If the target file already exists, it is overwritten. + /// + /// The file. + /// The string to write to. + /// http://msdn.microsoft.com/en-us/library/ms143375(v=vs.110).aspx + public static void WriteAllText(string path, string contents) + { + WriteAllText(new QuickIOPathInfo(path), contents); + } + + /// + /// Writes the specified string. + /// If the target file already exists, it is overwritten. + /// + /// The file. + /// The string to write to. + /// http://msdn.microsoft.com/en-us/library/ms143375(v=vs.110).aspx + public static void WriteAllText(QuickIOPathInfo pathInfo, string contents) + { + WriteAllText(pathInfo, contents, QuickIOSystemRules.UTF8EncodingNoEmit); + } + + /// + /// Writes the specified string. + /// If the target file already exists, it is overwritten. + /// + /// The file. + /// The string to write to. + /// The encoding to apply to the string. + /// http://msdn.microsoft.com/en-us/library/ms143376(v=vs.110).aspx + public static void WriteAllText(string path, string contents, Encoding encoding) + { + WriteAllText(new QuickIOPathInfo(path), contents, encoding); + } + + /// + /// Writes the specified string. + /// If the target file already exists, it is overwritten. + /// + /// The file. + /// The string to write to. + /// The encoding to apply to the string. + /// http://msdn.microsoft.com/en-us/library/ms143376(v=vs.110).aspx + public static void WriteAllText(QuickIOPathInfo pathInfo, string contents, Encoding encoding) + { + FileStream fileStream = OpenFileStream( pathInfo, FileAccess.ReadWrite, FileMode.Create, FileShare.None ); + using StreamWriter streamWriter = new(fileStream, encoding); + streamWriter.Write(contents); + } +} diff --git a/src/QuickIO/QuickIOFolderStatisticResult.cs b/src/QuickIO/QuickIOFolderStatisticResult.cs new file mode 100644 index 0000000..04697ce --- /dev/null +++ b/src/QuickIO/QuickIOFolderStatisticResult.cs @@ -0,0 +1,35 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Folder Statistics +/// +public class QuickIOFolderStatisticResult +{ + /// + /// Folder Count + /// + public ulong FolderCount { get; private set; } + + /// + /// File Count + /// + public ulong FileCount { get; private set; } + + /// + /// Total TotalBytes + /// + public ulong TotalBytes { get; private set; } + + /// + /// Creates new Instance of - internal access only + /// + /// Folder Count + /// File Count + /// Total TotalBytes + internal QuickIOFolderStatisticResult(ulong folderCount, ulong fileCount, ulong size) + { + FolderCount = folderCount; + FileCount = fileCount; + TotalBytes = size; + } +} diff --git a/src/QuickIO/QuickIOHashImplementationType.cs b/src/QuickIO/QuickIOHashImplementationType.cs new file mode 100644 index 0000000..644621b --- /dev/null +++ b/src/QuickIO/QuickIOHashImplementationType.cs @@ -0,0 +1,28 @@ +namespace SchwabenCode.QuickIO; + +/// +/// QuickIOHashImplementationType +/// +public enum QuickIOHashImplementationType +{ + /// + /// SHA1 + /// + SHA1, + /// + /// SHA256 + /// + SHA256, + /// + /// SHA384 + /// + SHA384, + /// + /// SHA512 + /// + SHA512, + /// + /// MD5 + /// + MD5 +} diff --git a/src/QuickIO/QuickIOHashResult.cs b/src/QuickIO/QuickIOHashResult.cs new file mode 100644 index 0000000..cdeb55d --- /dev/null +++ b/src/QuickIO/QuickIOHashResult.cs @@ -0,0 +1,95 @@ +using System.Text; + +namespace SchwabenCode.QuickIO; + +/// +/// This class is used for hash calculations. +/// Use +/// Format +/// +/// for human readable output. +/// +/// +/// +/// // Show human readable hash +/// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" ); +/// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8, "x2" ); +/// +/// +public class QuickIOHashResult +{ + /// + /// The bytes that represents the calculation result + /// + public byte[] HashBytes { get; private set; } + + /// + /// Creates an instance of + /// + /// + internal QuickIOHashResult(byte[] hashBytes) + { + HashBytes = hashBytes; + } + + /// + /// Formats the as a hexadecimal string using UTF8 encoding. + /// + /// Formated string + /// + /// + /// // Show human readable hash + /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" ); + /// Console.WriteLine("Hash: {0}", hashResult.Format( ); + /// + /// + public string Format() + { + return Format(Encoding.UTF8); + } + + /// + /// Formats the as a hexadecimal string using specified encoding. + /// + /// Encoding for formatting + /// Formated string + /// + /// + /// // Show human readable hash + /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" ); + /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8 ); + /// + /// + public string Format(Encoding encoding) + { + return Format(encoding, "x2"); + } + + /// + /// Formats the using specified encoding and format. + /// + /// Encoding for formatting + /// Pattern for formatting. Use x2 for hexadecimal output. + /// Formated string + /// + /// + /// // Show human readable hash + /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" ); + /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8, "x2" ); + /// + /// + public string Format(Encoding encoding, string format +, CancellationToken cancellationToken = default +) + { + StringBuilder sb = new( ); + for (int index = 0; index < HashBytes.Length; index++) + { + cancellationToken.ThrowIfCancellationRequested(); + + _ = sb.Append(HashBytes[index].ToString(format)); + } + + return sb.ToString(); + } +} diff --git a/src/QuickIO/QuickIOParsePathResult.cs b/src/QuickIO/QuickIOParsePathResult.cs new file mode 100644 index 0000000..42a2485 --- /dev/null +++ b/src/QuickIO/QuickIOParsePathResult.cs @@ -0,0 +1,55 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Result of parsing path +/// +public class QuickIOParsePathResult +{ + /// + /// Full root path + /// + /// C:\folder\parent\file.txt returns C:\ + /// Returns null if source path is Root + public string? RootPath { get; internal set; } + + /// + /// Full parent path + /// + /// C:\folder\parent\file.txt returns C:\folder\parent + /// Returns null if source path is Root + public string? ParentPath { get; internal set; } + + /// + /// Name of file or directory + /// + /// C:\folder\parent\file.txt returns file.txt + /// C:\folder\parent returns parent + /// Returns null if source path is Root + public string? Name { get; internal set; } + + /// + /// True if source path is root + /// + public bool IsRoot { get; internal set; } + + /// + /// Full path without trailing directory separtor char + /// + public string FullName { get; internal set; } = null!; + + /// + /// Full UNC path without trailing directory separtor char + /// + public string FullNameUnc { get; internal set; } = null!; + + /// + /// + /// + public QuickIOPathType PathType { get; internal set; } + + /// + /// + /// + public QuickIOPathLocation PathLocation { get; internal set; } + +} diff --git a/src/QuickIO/QuickIOPath.cs b/src/QuickIO/QuickIOPath.cs new file mode 100644 index 0000000..105ee6c --- /dev/null +++ b/src/QuickIO/QuickIOPath.cs @@ -0,0 +1,610 @@ +using System.Diagnostics.CodeAnalysis; +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +/// +/// Performs operations for files or directories and path information. +/// +public static class QuickIOPath +{ + /// + /// Maximum allowed length of a regular path + /// + public const int MaxRegularPathLength = 260; + + /// + /// Maximum allowed length of a regular folder path + /// + public const int MaxSimpleDirectoryPathLength = 247; + + /// + /// Maximum allowed length of an UNC Path + /// + public const int MaxUncPathLength = 32767; + + /// + /// Regular local path prefix + /// + public const string RegularLocalPathPrefix = @""; + + /// + /// Path prefix for shares + /// + public const string RegularSharePathPrefix = @"\\"; + + /// + /// Length of Path prefix for shares + /// + public static readonly int RegularSharePathPrefixLength = RegularSharePathPrefix.Length; + + /// + /// UNC prefix for regular paths + /// + public const string UncLocalPathPrefix = @"\\?\"; + + /// + /// Length of UNC prefix for regular paths + /// + public static readonly int UncLocalPathPrefixLength = UncLocalPathPrefix.Length; + + /// + /// UNC prefix for shares + /// + public const string UncSharePathPrefix = @"\\?\UNC\"; + + /// + /// Length of UNC prefix for shares + /// + public static readonly int UncSharePathPrefixLength = UncSharePathPrefix.Length; + + /// + /// Directory Separator Char + /// + public static char DirectorySeparatorChar = System.IO.Path.DirectorySeparatorChar; + + /// + /// Checks if path exists + /// + /// Path to check + /// True on exists + public static bool Exists(string path) + { + return InternalQuickIO.Exists(path); + } + + /// + /// Converts unc path to regular path + /// + public static string ToRegularPath(string anyFullname) + { + // First: Check for UNC QuickIOShareInfo + if (anyFullname.StartsWith(QuickIOPath.UncSharePathPrefix)) + { + return QuickIOPath.ToShareRegularPath(anyFullname); // Convert + } + // Check for local UNC usage + if (anyFullname.StartsWith(QuickIOPath.UncLocalPathPrefix)) + { + return QuickIOPath.ToLocalRegularPath(anyFullname); // Convert + } + + return anyFullname; + } + + /// + /// Converts regular path to unc path + /// + public static string ToUncPath(string anyFullname) + { + // Check for regular share usage + if (anyFullname.StartsWith(QuickIOPath.UncSharePathPrefix)) + { + // it's an unc share, do not edit! + return anyFullname; + } + if (anyFullname.StartsWith(QuickIOPath.UncLocalPathPrefix)) + { + // it's an unc local, do not edit! + return anyFullname; + } + + if (anyFullname.StartsWith(QuickIOPath.RegularSharePathPrefix)) + { + return QuickIOPath.ToShareUncPath(anyFullname); // Convert + } + // ehmm.. must be local regular path + if (anyFullname.StartsWith(QuickIOPath.RegularLocalPathPrefix)) + { + return QuickIOPath.ToLocalUncPath(anyFullname); // Convert + } + + return anyFullname; + } + + + /// + /// Converts an unc path to a local regular path + /// + /// Unc Path + /// \\?\C:\temp\file.txt >> C:\temp\file.txt + /// Local Regular Path + public static string ToLocalRegularPath(string uncLocalPath) + { + return uncLocalPath.Substring(UncLocalPathPrefix.Length); + } + + /// + /// Converts an unc path to a share regular path + /// + /// Unc Path + /// \\?\UNC\server\share >> \\server\share + /// QuickIOShareInfo Regular Path + public static string ToShareRegularPath(string uncSharePath) + { + return RegularSharePathPrefix + uncSharePath.Substring(UncSharePathPrefix.Length); + } + + /// + /// Converts a regular local path to an unc path + /// + /// Regular Path + /// C:\temp\file.txt >> \\?\C:\temp\file.txt + /// Local Unc Path + public static string ToLocalUncPath(string regularLocalPath) + { + return UncLocalPathPrefix + regularLocalPath; + } + + /// + /// Converts a regular share path to an unc path + /// + /// Regular Path + /// \\server\share\file.txt >> \\?\UNC\server\share\file.txt + /// QuickIOShareInfo Unc Path + public static string ToShareUncPath(string regularSharePath) + { + return UncSharePathPrefix + regularSharePath.Substring(2); + } + + /// + /// Gets name of file or directory + /// + /// Path + /// Name of file or directory + /// Path is invalid + public static string GetName(string fullName) + { + string path = TrimTrailingSepartor( fullName ); + int sepPosition = path.LastIndexOf( Path.DirectorySeparatorChar ); + + return sepPosition == -1 ? path : path.Substring(sepPosition + 1); + } + + /// + /// A wrapper for + /// + public static string GetFullPath(string path) + { + return Path.GetFullPath(path); + } + + /// + /// A wrapper for that returns + /// + public static QuickIOPathInfo GetFullPathInfo(string path) + { + return new QuickIOPathInfo(Path.GetFullPath(path)); + } + + /// + /// Removes Last + /// + private static string TrimTrailingSepartor(string path) + { + return path.TrimEnd(Path.DirectorySeparatorChar); + } + + /// + /// Returns root from path by given location type + /// + public static string GetRootFromLocalPath(string path, QuickIOPathLocation location) + { + switch (location) + { + case QuickIOPathLocation.Local: + { + return path.Substring(0, 3); + } + case QuickIOPathLocation.Share: + { + string[] pathElements = path.Substring( 2 ).Split( Path.DirectorySeparatorChar ); + if (pathElements.Length < 2) + { + throw new InvalidPathException(path, "Path is invalid for Location " + location); + } + return RegularSharePathPrefix + pathElements[0] + Path.DirectorySeparatorChar + pathElements[1]; + } + } + + throw new ArgumentException("QuickIOPathLocation " + location + " not supported."); + } + + /// + /// Invalid Chars are: " < > | and all chars lower than ASCII value 32 + /// + /// Ignores Unix File Systems + /// Path to check + /// If invalid character found + public static void ThrowIfPathContainsInvalidChars(string path) + { + for (int index = 0; index < path.Length; index++) + { + char currentChar = path[ index ]; + if (currentChar < 32 || currentChar == '\"' || currentChar == '<' || currentChar == '>' || currentChar == '|') + { + throw new InvalidPathException("Path contains invalid characters", path); + } + } + } + + /// + /// Combines given path elements + /// + /// Path elements to combine + /// Combined Path + public static string Combine(params string[] pathElements) + { + if (pathElements == null || pathElements.Length == 0) + { + throw new ArgumentNullException(nameof(pathElements), "Cannot be null or empty"); + } + + // Verify not required; System.IO.Path.Combine calls internal path invalid char verifier + + // First Element + string combinedPath = pathElements[ 0 ]; + + // Other elements + for (int i = 1; i < pathElements.Length; i++) + { + string el = pathElements[ i ]; + + // Combine + combinedPath = Path.Combine(combinedPath, el); + } + + return combinedPath; + } + + /// + /// Returns + /// + /// + public static string GetRandomFileName() + { + return Path.GetRandomFileName(); + } + + /// + /// Returns without extension + /// + /// without extension + public static string GetRandomDirectoryName() + { + return Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); + } + + /// + /// Returns the parent directory path + /// + /// Path to get the parent from + /// Parent directory + public static string? GetParentPath(string fullName) + { + return new QuickIOPathInfo(fullName).ParentFullName; + } + + /// + /// Returns the root directory path + /// + /// Path to get the parent from + /// Root directory + public static string? GetRoot(string fullName) + { + return new QuickIOPathInfo(fullName).RootFullName; + } + + + /// + /// Returns true if path is local regular path such as 'C:\folder\folder\file.txt' + /// + /// Path + /// True if path is local regular path + public static bool IsLocalRegularPath(string path) + { + return (path.Length >= 3 && char.IsLetter(path[0]) && path[1] == ':' && path[2] == Path.DirectorySeparatorChar); + } + + /// + /// Returns true if path is local UNC path such as '\\?\C:\folder\folder\file.txt' + /// + /// Path + /// True if path is local UNC path + public static bool IsLocalUncPath(string path) + { + return (path.Length >= 7 && path[0] == '\\' && path[1] == '\\' && (path[2] == '?' || path[2] == '.') && path[3] == '\\' && IsLocalRegularPath(path.Substring(4))); + } + + + + /// + /// Returns true if path is share regular path such as '\\server\share\folder\file.txt' + /// + /// Path + /// True if path is share regular path + public static bool IsShareRegularPath(string path) + { + if (!path.StartsWith(QuickIOPath.RegularSharePathPrefix)) + { + return false; + } + if (path.StartsWith(QuickIOPath.UncSharePathPrefix)) + { + return false; + } + + string[] pathElements = path.Substring( QuickIOPath.RegularSharePathPrefixLength ).Split( '\\' ); + return (pathElements.Length >= 2); + } + + /// + /// Returns true if path is share UNC path such as '\\?\UNC\server\share\folder\file.txt' + /// + /// Path + /// True if path is share UNC path + public static bool IsShareUncPath(string path) + { + if (!path.StartsWith(QuickIOPath.UncSharePathPrefix)) + { + return false; + } + + string[] pathElements = path.Substring( QuickIOPath.UncSharePathPrefixLength ).Split( '\\' ); + return (pathElements.Length >= 2); + } + + /// + /// Try to parse path + /// + /// Path to parse + /// Result. See + /// true to support relative path + /// True on success. is set. + public static bool TryParsePath(string path, [NotNullWhen(true)] out QuickIOParsePathResult? parsePathResult, bool supportRelativePath = true) + { + if (QuickIOPath.TryParseLocalRegularPath(path, out parsePathResult)) + { + return true; + } + + if (QuickIOPath.TryParseLocalUncPath(path, out parsePathResult)) + { + return true; + } + if (QuickIOPath.TryParseShareRegularPath(path, out parsePathResult)) + { + return true; + } + if (QuickIOPath.TryParseShareUncPath(path, out parsePathResult)) + { + return true; + } + + if (supportRelativePath && QuickIOPath.TryParseLocalRegularPath(Path.GetFullPath(path), out parsePathResult)) + { + return true; + } + + return false; + } + + public static QuickIOParsePathResult ParsePath(string path, bool supportRelativePath = true) + { + if (!QuickIOPath.TryParsePath(path, out QuickIOParsePathResult? result)) + { + throw new InvalidPathException(path); + } + + return result; + } + + + /// + /// Returns true if specified is local regular path and returns result due to + /// + /// Local path to parse + /// + /// True if parse succeeded and is filled + public static bool TryParseLocalRegularPath(string path, [NotNullWhen(true)] out QuickIOParsePathResult? parsePathResult) + { + if (!IsLocalRegularPath(path)) + { + parsePathResult = null; + return false; + } + + parsePathResult = new QuickIOParsePathResult { PathLocation = QuickIOPathLocation.Local, PathType = QuickIOPathType.Regular }; + + if (path.Length == 3) + { + parsePathResult.IsRoot = true; + parsePathResult.ParentPath = null; + parsePathResult.RootPath = null; + parsePathResult.Name = null; + parsePathResult.FullNameUnc = QuickIOPath.UncLocalPathPrefix + path; + parsePathResult.FullName = path; + } + else + { + parsePathResult.IsRoot = false; + parsePathResult.FullName = path.TrimEnd(Path.DirectorySeparatorChar); + parsePathResult.FullNameUnc = QuickIOPath.UncLocalPathPrefix + parsePathResult.FullName; + parsePathResult.ParentPath = parsePathResult.FullName.Substring(0, parsePathResult.FullName.LastIndexOf(Path.DirectorySeparatorChar)); + parsePathResult.RootPath = path.Substring(0, 3); + + parsePathResult.Name = parsePathResult.FullName.Substring(parsePathResult.FullName.LastIndexOf(Path.DirectorySeparatorChar) + 1); + } + + return true; + } + + /// + /// Returns true if specified is local UNC path and returns result due to + /// + /// Local UNC path to parse + /// + /// True if parse succeeded and is filled + public static bool TryParseLocalUncPath(string path, [NotNullWhen(true)] out QuickIOParsePathResult? parsePathResult) + { + if (!IsLocalUncPath(path)) + { + parsePathResult = null; + return false; + } + + parsePathResult = new QuickIOParsePathResult { PathLocation = QuickIOPathLocation.Local, PathType = QuickIOPathType.UNC }; + + if (path.Length == 7) + { + parsePathResult.IsRoot = true; + parsePathResult.ParentPath = null; + parsePathResult.RootPath = null; + + parsePathResult.FullNameUnc = path; + parsePathResult.FullName = path.Substring(4); + parsePathResult.Name = null; + } + else + { + parsePathResult.IsRoot = false; + parsePathResult.FullNameUnc = path.TrimEnd(Path.DirectorySeparatorChar); + parsePathResult.FullName = parsePathResult.FullNameUnc.Substring(4); + + parsePathResult.ParentPath = parsePathResult.FullName.Substring(0, parsePathResult.FullName.LastIndexOf(Path.DirectorySeparatorChar)); + parsePathResult.RootPath = path.Substring(4, 3); + + parsePathResult.Name = parsePathResult.FullName.Substring(parsePathResult.FullName.LastIndexOf(Path.DirectorySeparatorChar) + 1); + } + + return true; + } + + /// + /// Returns true if specified is share regular path and returns result due to + /// + /// QuickIOShareInfo regular path to parse + /// + /// True if parse succeeded and is filled + public static bool TryParseShareRegularPath(string path, [NotNullWhen(true)] out QuickIOParsePathResult? parsePathResult) + { + if (!IsShareRegularPath(path)) + { + parsePathResult = null; + return false; + } + + parsePathResult = new QuickIOParsePathResult { PathLocation = QuickIOPathLocation.Share, PathType = QuickIOPathType.Regular }; + + string cleanedPath = path.TrimEnd( '\\' ); + + string[] pathElements = cleanedPath.Substring( QuickIOPath.RegularSharePathPrefixLength ).Split( '\\' ); + + string server = pathElements[ 0 ]; + string name = pathElements[ 1 ]; + + string rootPath = QuickIOPath.RegularSharePathPrefix + server + @"\" + name; + + string completePath = rootPath; + for (int i = 2; i < pathElements.Length; i++) + { + completePath += "\\" + pathElements[i]; + } + + // set + parsePathResult.IsRoot = (cleanedPath == rootPath); + + if (parsePathResult.IsRoot) + { + parsePathResult.ParentPath = null; + parsePathResult.RootPath = null; + parsePathResult.Name = null; + parsePathResult.FullNameUnc = QuickIOPath.UncSharePathPrefix + server + @"\" + name; + parsePathResult.FullName = QuickIOPath.RegularSharePathPrefix + server + @"\" + name; + } + else + { + parsePathResult.FullName = cleanedPath; + parsePathResult.FullNameUnc = QuickIOPath.UncSharePathPrefix + cleanedPath.Substring(2); + parsePathResult.ParentPath = completePath.Substring(0, completePath.LastIndexOf(Path.DirectorySeparatorChar)); + parsePathResult.RootPath = rootPath; + + parsePathResult.Name = pathElements[pathElements.Length - 1]; + } + + return true; + } + + /// + /// Returns true if specified is share UNC path and returns result due to + /// + /// QuickIOShareInfo UNC path to parse + /// + /// True if parse succeeded and is filled + public static bool TryParseShareUncPath(string path, [NotNullWhen(true)] out QuickIOParsePathResult? parsePathResult) + { + if (!IsShareUncPath(path)) + { + parsePathResult = null; + return false; + } + + parsePathResult = new QuickIOParsePathResult { PathLocation = QuickIOPathLocation.Share, PathType = QuickIOPathType.UNC }; + + string cleanedPath = path.TrimEnd( '\\' ); + + string[] pathElements = cleanedPath.Substring( QuickIOPath.UncSharePathPrefixLength ).Split( '\\' ); + + string server = pathElements[ 0 ]; + string name = pathElements[ 1 ]; + + string completeRelativePath = server + @"\" + name; + for (int i = 2; i < pathElements.Length; i++) + { + completeRelativePath += "\\" + pathElements[i]; + } + + // set + parsePathResult.IsRoot = (cleanedPath == (QuickIOPath.UncSharePathPrefix + server + @"\" + name)); + + if (parsePathResult.IsRoot) + { + parsePathResult.ParentPath = null; + parsePathResult.RootPath = null; + parsePathResult.Name = null; + parsePathResult.FullNameUnc = QuickIOPath.UncSharePathPrefix + server + @"\" + name; + parsePathResult.FullName = QuickIOPath.RegularSharePathPrefix + server + @"\" + name; + } + else + { + parsePathResult.FullName = QuickIOPath.RegularSharePathPrefix + completeRelativePath; + parsePathResult.FullNameUnc = QuickIOPath.UncSharePathPrefix + completeRelativePath; + parsePathResult.ParentPath = QuickIOPath.RegularSharePathPrefix + completeRelativePath.Substring(0, completeRelativePath.LastIndexOf(Path.DirectorySeparatorChar)); + parsePathResult.RootPath = QuickIOPath.RegularSharePathPrefix + server + @"\" + name; + + parsePathResult.Name = pathElements[pathElements.Length - 1]; + } + + return true; + } +} diff --git a/src/QuickIO/QuickIOPathInfo.cs b/src/QuickIO/QuickIOPathInfo.cs new file mode 100644 index 0000000..a42176d --- /dev/null +++ b/src/QuickIO/QuickIOPathInfo.cs @@ -0,0 +1,238 @@ +using System.Security.Principal; +using SchwabenCode.QuickIO.Internal; +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +/// +/// Provides properties and instance method for paths +/// +public sealed class QuickIOPathInfo +{ + /// + /// Creates the path information container + /// + /// Full path to the file or directory (regular or unc) + public QuickIOPathInfo(string anyFullname) + : this(anyFullname, QuickIOPath.GetName(anyFullname)) + { + QuickIOPath.ThrowIfPathContainsInvalidChars(anyFullname); + } + + /// + /// Creates the path information container + /// + /// Full path to the file or directory (regular or unc). Relative path will be recognized as local regular path. + /// Name of file or directory + public QuickIOPathInfo(string anyFullname, string name) + { + if (!QuickIOPath.TryParsePath(anyFullname, out QuickIOParsePathResult? parsePathResult, supportRelativePath: true)) + { + // Unknown path + throw new InvalidPathException("Unable to parse path", anyFullname); + } + + FullNameUnc = parsePathResult.FullNameUnc; + FullName = parsePathResult.FullName; + ParentFullName = parsePathResult.ParentPath; + RootFullName = parsePathResult.RootPath; + IsRoot = parsePathResult.IsRoot; + PathLocation = parsePathResult.PathLocation; + Name = name; + PathType = parsePathResult.PathType; + + if (PathLocation == QuickIOPathLocation.Local) + { + string testRoot = (IsRoot ? FullName : RootFullName)!; + + string[] allDrives = Environment.GetLogicalDrives(); + bool exists = Array.Exists(allDrives,(string drve) => drve.Equals(testRoot, StringComparison.OrdinalIgnoreCase)); + if (exists is false) + { + throw new UnsupportedDriveTypeException(testRoot); + } + } + } + + /// + /// Path to file or directory (regular format) + /// + public string FullName { get; private set; } + + /// + /// Path to file or directory (unc format) + /// + public string FullNameUnc { get; private set; } + + /// + /// Name of file or directory + /// + public string Name { get; private set; } + + /// + /// + /// + public QuickIOPathType PathType { get; private set; } + + /// + /// Fullname of Root. null if current path is root. + /// + public string? RootFullName { get; private set; } + + /// + /// Fullname of Parent. null if current path is root. + /// + public string? ParentFullName { get; set; } + + /// + /// Parent Directory + /// + public QuickIOPathInfo? Parent + => ParentFullName == null ? null : new QuickIOPathInfo(ParentFullName); + + /// + /// of current path + /// + public QuickIOPathLocation PathLocation { get; private set; } + + /// + /// FindData + /// + internal Win32FindData FindData + { + get + { + if (IsRoot) + { + throw new NotSupportedException("Root directory does not provide owner access"); + } + return _findData ??= InternalQuickIO.GetFindDataFromPath(this); + } + set + { + _findData = value; + } + } + private Win32FindData? _findData; + + /// + /// Attributes. Cached. + /// + /// if path is root + public FileAttributes Attributes + { + get + { + if (IsRoot) + { + throw new NotSupportedException("Root directory does not provide attributes"); + } + return FindData.dwFileAttributes; + } + } + + /// + /// Returns true if current path is root + /// + public bool IsRoot { get; private set; } + + /// + /// Returns Root or null if current path is root + /// + public QuickIOPathInfo? Root + { + get { return (RootFullName == null ? null : new QuickIOPathInfo(RootFullName)); } + } + + /// + /// Returns true if path exists. Checks + /// + /// + public bool Exists + { + get + { + return InternalQuickIO.Exists(this); + } + } + + ///// + ///// Returns true if path exists. Checks + ///// + ///// + //public Boolean CheckExistance( QuickIOFileSystemEntryType? systemEntryType = null ) + //{ + // return systemEntryType == null ? InternalQuickIO.Exists( this ) : InternalQuickIOCommon.Exists( FullNameUnc, ( QuickIOFileSystemEntryType ) systemEntryType ); + //} + + /// + /// Returns true if path exists. Checks against the file system + /// + public QuickIOFileSystemEntryType SystemEntryType + { + get + { + return InternalQuickIOCommon.DetermineFileSystemEntry(this); + } + + } + + /// + /// Returns current + /// + /// + public QuickIOFileSystemSecurity GetFileSystemSecurity() + { + return new QuickIOFileSystemSecurity(this); + } + + /// + /// Determines the owner + /// + /// + public NTAccount? GetOwner() + { + if (IsRoot) + { + throw new NotSupportedException("Root directory does not provide owner access"); + } + return GetOwnerIdentifier()?.Translate(typeof(NTAccount)) as NTAccount; + } + + /// + /// Determines the owner + /// + /// + public IdentityReference? GetOwnerIdentifier() + { + if (IsRoot) + { + throw new NotSupportedException("Root directory does not provide owner access"); + } + return GetFileSystemSecurity().FileSystemSecurityInformation.GetOwner(typeof(SecurityIdentifier)); + } + + /// + /// Sets the owner + /// + public void SetOwner(NTAccount newOwner) + { + if (IsRoot) + { + throw new NotSupportedException("Root directory does not provide owner access"); + } + GetFileSystemSecurity().FileSystemSecurityInformation.SetOwner(newOwner.Translate(typeof(SecurityIdentifier))); + } + + /// + /// Sets the owner + /// + public void SetOwner(IdentityReference newOwersIdentityReference) + { + if (IsRoot) + { + throw new NotSupportedException("Root directory does not provide owner access"); + } + GetFileSystemSecurity().FileSystemSecurityInformation.SetOwner(newOwersIdentityReference); + } +} diff --git a/src/QuickIO/QuickIOPathLocation.cs b/src/QuickIO/QuickIOPathLocation.cs new file mode 100644 index 0000000..ef3d993 --- /dev/null +++ b/src/QuickIO/QuickIOPathLocation.cs @@ -0,0 +1,17 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Path Location (Local, QuickIOShareInfo) +/// +/// http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx +public enum QuickIOPathLocation +{ + /// + /// Represents Local Path + /// + Local, + /// + /// Represents Network QuickIOShareInfo + /// + Share +} diff --git a/src/QuickIO/QuickIOPathType.cs b/src/QuickIO/QuickIOPathType.cs new file mode 100644 index 0000000..2f83ff7 --- /dev/null +++ b/src/QuickIO/QuickIOPathType.cs @@ -0,0 +1,17 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Path Types (Regular or UNC ) +/// +/// http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx +public enum QuickIOPathType +{ + /// + /// Regular + /// + Regular, + /// + /// UNC + /// + UNC +} diff --git a/src/QuickIO/QuickIOPatternConstants.cs b/src/QuickIO/QuickIOPatternConstants.cs new file mode 100644 index 0000000..93ca587 --- /dev/null +++ b/src/QuickIO/QuickIOPatternConstants.cs @@ -0,0 +1,12 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Various constants for filter +/// +public static class QuickIOPatternConstants +{ + /// + /// Matches all. No filtering. + /// + public const string All = "*"; +} diff --git a/src/QuickIO/QuickIOPatterns.cs b/src/QuickIO/QuickIOPatterns.cs new file mode 100644 index 0000000..9e5b1ef --- /dev/null +++ b/src/QuickIO/QuickIOPatterns.cs @@ -0,0 +1,65 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Pattern Collection +/// +public static class QuickIOPatterns +{ + /// + /// Pattern to match IPv6 + /// + /// ([\da-fA-F]{1,4}(\:[\da-fA-F]{1,4}){7})|(([\da-fA-F]{1,4}:){0,5}::([\da-fA-F]{1,4}:){0,5}[\da-fA-F]{1,4}) + public const string IPv6Pattern = @"([\da-fA-F]{1,4}(\:[\da-fA-F]{1,4}){7})|(([\da-fA-F]{1,4}:){0,5}::([\da-fA-F]{1,4}:){0,5}[\da-fA-F]{1,4})"; + + /// + /// Pattern to match IPv4 + /// + /// (((([1]?\d)?\d|2[0-4]\d|25[0-5])\.){3}(([1]?\d)?\d|2[0-4]\d|25[0-5])) + public const string IPv4Pattern = @"(((([1]?\d)?\d|2[0-4]\d|25[0-5])\.){3}(([1]?\d)?\d|2[0-4]\d|25[0-5]))"; + + /// + /// Pattern to match IPv4 and IPv6 + /// + /// ([\da-fA-F]{1,4}(\:[\da-fA-F]{1,4}){7})|(([\da-fA-F]{1,4}:){0,5}::([\da-fA-F]{1,4}:){0,5}[\da-fA-F]{1,4})|(((([1]?\d)?\d|2[0-4]\d|25[0-5])\.){3}(([1]?\d)?\d|2[0-4]\d|25[0-5])) + public const string IPv4v6Pattern = IPv4Pattern + @"|" + IPv6Pattern; + + /// + /// Matching Server Name + /// + /// [a-zA-Z0-9_]+ + public const string ServerNamePattern = @"[a-zA-Z0-9_]+"; + /// + /// Matching QuickIOShareInfo Name + /// + /// [a-zA-Z0-9_]+ + public const string ShareNamePattern = @"[a-zA-Z0-9_]+"; + /// + /// Matching Folder Name + /// + /// [a-zA-Z0-9_]+ + public const string FolderNamePattern = @"[a-zA-Z0-9_]+"; + + /// + /// Optional UNC Separator + /// + /// \\{0,1} + public const string OptionalSperatorPattern = @"\\{0,1}"; + + /// + /// Pattern matching share root + /// + public const string RegularShareRootPattern = @"(?\\\\(?" + ServerNamePattern + @"|" + IPv4v6Pattern + @")\\(?" + ShareNamePattern + @"))" + OptionalSperatorPattern; + + /// + /// Pattern matching share path + /// + public const string RegularSharePattern = @"(?" + RegularShareRootPattern + @"\\{0,1}(?((\\(" + FolderNamePattern + @")){0,})))" + OptionalSperatorPattern; + + /// + /// Returns ^$ + /// + public static string GetStrict(string pattern) + { + return "^" + pattern + "$"; + } +} diff --git a/src/QuickIO/QuickIORecommendedValues.cs b/src/QuickIO/QuickIORecommendedValues.cs new file mode 100644 index 0000000..6fd2244 --- /dev/null +++ b/src/QuickIO/QuickIORecommendedValues.cs @@ -0,0 +1,28 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Various default and recommended values for different operations, connections and API calls +/// +public static class QuickIORecommendedValues +{ + /// + /// Recommended buffer byte size for default read operations + /// + public const int DefaultReadBufferBytes = 4096; + + /// + /// Recommended size of Byte packages for TCP connections + /// + public const int TCPMaxPackageBytes = 65535; + + /// + /// Recommended size of Byte packages for local ethernet connections + /// + public const int MTUMaxPackageBytes = 1500; + + /// + /// Recommended size of Byte packages for SMB connections + /// + /// See http://support.microsoft.com/kb/223140 + public const int SMBMaxPackageBytes = 60 * 1024; +} diff --git a/src/QuickIO/QuickIOShare.cs b/src/QuickIO/QuickIOShare.cs new file mode 100644 index 0000000..f3c7ea0 --- /dev/null +++ b/src/QuickIO/QuickIOShare.cs @@ -0,0 +1,34 @@ +using System.Runtime.InteropServices; +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +/// +/// Provides static methods to access network shares. +/// +public static partial class QuickIOShare +{ + /// + /// Checks the given share for admin information + /// + /// Sharename + /// Share reference + /// + internal static QuickIOShareInfo GetShareInfoWithAdminInformation(string serverName, IntPtr item) + { + Win32ApiShareInfoAdmin shareInfo = ( Win32ApiShareInfoAdmin ) Marshal.PtrToStructure( item, typeof( Win32ApiShareInfoAdmin ) )!; + return new QuickIOShareInfo(serverName, shareInfo.ShareName, shareInfo.ShareType, shareInfo.Remark); + } + + /// + /// Checks the given share for normal user information + /// + /// Sharename + /// Share reference + /// + internal static QuickIOShareInfo GetShareInfoWithNormalInformation(string serverName, IntPtr item) + { + Win32ApiShareInfoNormal shareInfo = ( Win32ApiShareInfoNormal ) Marshal.PtrToStructure( item, typeof( Win32ApiShareInfoNormal ) )!; + return new QuickIOShareInfo(serverName, shareInfo.ShareName, shareInfo.ShareType, shareInfo.Remark); + } +} diff --git a/src/QuickIO/QuickIOShareApiReadLevel.cs b/src/QuickIO/QuickIOShareApiReadLevel.cs new file mode 100644 index 0000000..e15f5c3 --- /dev/null +++ b/src/QuickIO/QuickIOShareApiReadLevel.cs @@ -0,0 +1,13 @@ +namespace SchwabenCode.QuickIO; + +public enum QuickIOShareApiReadLevel : int +{ + /// + /// Requests all information and required admin privilegs + /// + Admin = 2, + /// + /// Default call type + /// + Normal = 1 +} diff --git a/src/QuickIO/QuickIOShareInfo.cs b/src/QuickIO/QuickIOShareInfo.cs new file mode 100644 index 0000000..7fc89ca --- /dev/null +++ b/src/QuickIO/QuickIOShareInfo.cs @@ -0,0 +1,87 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Information about a local share +/// +public partial class QuickIOShareInfo +{ + /// + /// Called by enumeration + /// + /// Servername + /// Name of Share + /// Type of share + /// Comment or smth + internal QuickIOShareInfo(string server, string shareName, QuickIOShareType shareType, string remark) + { + if (QuickIOShareType.Special == shareType && "IPC$" == shareName) + { + shareType = QuickIOShareType.IPC; + } + + Server = server; + ShareName = shareName; + ShareType = shareType; + Remark = remark; + } + + /// + /// The name of the computer that this share belongs to + /// + public string Server { get; private set; } + + /// + /// QuickIOShareInfo name + /// + public string ShareName { get; private set; } + + /// + /// QuickIOShareInfo type + /// + public QuickIOShareType ShareType { get; private set; } + + /// + /// Comment + /// + public string Remark { get; private set; } + + /// + /// Returns true if this is a file system share + /// + public bool IsFileSystem + { + get + { + if (ShareType == QuickIOShareType.Disk) + { + return true; + } + + // Handle local special shares like C$ + if (QuickIOShareType.Special == ShareType && !string.IsNullOrEmpty(ShareName)) + { + return true; + } + + return false; + } + } + + + /// + /// Returns the path to this share + /// + /// + public override string ToString() + { + return FullName; + } + + /// + /// Returns the path + /// + public string FullName + { + get { return string.Format(@"\\{0}\{1}", string.IsNullOrEmpty(Server) ? Environment.MachineName : Server, ShareName); } + } +} diff --git a/src/QuickIO/QuickIOShareInfo_DiskInformation.cs b/src/QuickIO/QuickIOShareInfo_DiskInformation.cs new file mode 100644 index 0000000..a237648 --- /dev/null +++ b/src/QuickIO/QuickIOShareInfo_DiskInformation.cs @@ -0,0 +1,22 @@ +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIOShareInfo +{ + /// + /// Returns of this instance. + /// + /// + /// Only supported for + /// Metadata not supported for this Sharetype. Only available for + public QuickIODiskInformation GetDiskInformation() + { + if (ShareType != QuickIOShareType.Disk) + { + throw new UnsupportedShareTypeException(FullName, "Metadata not supported for this Sharetype"); + } + + return InternalQuickIO.GetDiskInformation(FullName); + } +} diff --git a/src/QuickIO/QuickIOShareInfo_DiskInformation_Async.cs b/src/QuickIO/QuickIOShareInfo_DiskInformation_Async.cs new file mode 100644 index 0000000..a31ae23 --- /dev/null +++ b/src/QuickIO/QuickIOShareInfo_DiskInformation_Async.cs @@ -0,0 +1,17 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIOShareInfo +{ + /// + /// Returns of this instance. + /// + /// + /// Only supported for + /// Metadata not supported for this Sharetype. Only available for + public Task GetDiskInformationAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(GetDiskInformation); + } +} diff --git a/src/QuickIO/QuickIOShareInfo_Operators.cs b/src/QuickIO/QuickIOShareInfo_Operators.cs new file mode 100644 index 0000000..2d9966f --- /dev/null +++ b/src/QuickIO/QuickIOShareInfo_Operators.cs @@ -0,0 +1,13 @@ +namespace SchwabenCode.QuickIO; + +public partial class QuickIOShareInfo +{ + /// + /// Returns a of the current path of this file + /// + /// + public QuickIODirectoryInfo AsDirectoryInfo() + { + return new QuickIODirectoryInfo(FullName); + } +} diff --git a/src/QuickIO/QuickIOShareInfo_Operators_Async.cs b/src/QuickIO/QuickIOShareInfo_Operators_Async.cs new file mode 100644 index 0000000..24e037f --- /dev/null +++ b/src/QuickIO/QuickIOShareInfo_Operators_Async.cs @@ -0,0 +1,15 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public partial class QuickIOShareInfo +{ + /// + /// Returns a of the current path of this file + /// + /// + public Task AsDirectoryInfoAsync() + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(AsDirectoryInfo); + } +} diff --git a/src/QuickIO/QuickIOShareMetadata_Async.cs b/src/QuickIO/QuickIOShareMetadata_Async.cs new file mode 100644 index 0000000..cc0124a --- /dev/null +++ b/src/QuickIO/QuickIOShareMetadata_Async.cs @@ -0,0 +1,6 @@ +namespace SchwabenCode.QuickIO; + +public sealed partial class QuickIODiskInformation +{ + +} diff --git a/src/QuickIO/QuickIOShareType.cs b/src/QuickIO/QuickIOShareType.cs new file mode 100644 index 0000000..5411e2e --- /dev/null +++ b/src/QuickIO/QuickIOShareType.cs @@ -0,0 +1,31 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Enum collection of available shares types +/// +public enum QuickIOShareType : uint +{ + /// + /// Disk or network share share + /// + Disk = 0, + + /// + /// Printer share + /// + Printer = 1, + + /// + /// Device share + /// + Device = 2, + + /// + /// IPC share + IPC = 2147483651, + + /// + /// Special share + /// + Special = 2147483648 +} diff --git a/src/QuickIO/QuickIOShare_DiskInformation.cs b/src/QuickIO/QuickIOShare_DiskInformation.cs new file mode 100644 index 0000000..c5cd227 --- /dev/null +++ b/src/QuickIO/QuickIOShare_DiskInformation.cs @@ -0,0 +1,16 @@ +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIOShare +{ + /// + /// Receives of specifies share path + /// + /// + /// See http://support.microsoft.com/kb/231497 + public static QuickIODiskInformation GetDiskInformation(string sharePath) + { + return InternalQuickIO.GetDiskInformation(sharePath); + } +} diff --git a/src/QuickIO/QuickIOShare_DiskInformation_Async.cs b/src/QuickIO/QuickIOShare_DiskInformation_Async.cs new file mode 100644 index 0000000..6669edd --- /dev/null +++ b/src/QuickIO/QuickIOShare_DiskInformation_Async.cs @@ -0,0 +1,16 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIOShare +{ + /// + /// Receives of specifies share path + /// + /// + /// See http://support.microsoft.com/kb/231497 + public static Task GetMetadataAsync(string sharePath) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetDiskInformation(sharePath)); + } +} diff --git a/src/QuickIO/QuickIOShare_Enumerate.cs b/src/QuickIO/QuickIOShare_Enumerate.cs new file mode 100644 index 0000000..7cea355 --- /dev/null +++ b/src/QuickIO/QuickIOShare_Enumerate.cs @@ -0,0 +1,76 @@ +using System.Runtime.InteropServices; +using SchwabenCode.QuickIO.Internal; +using SchwabenCode.QuickIO.Win32API; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIOShare +{ + + /// + /// Enumerate shares of specific machine. If no machine is specified, local machine is used + /// + /// Collection of + public static IEnumerable EnumerateShares(string? machineName = null, QuickIOShareApiReadLevel level = QuickIOShareApiReadLevel.Admin) + { + // Specify + string targetName = string.IsNullOrEmpty( machineName ) ? Environment.MachineName : machineName; + + int resumeHandle = 0; + nint buffer = IntPtr.Zero; + + try + { + int entriesRead = 0; + int totalEntries = 0; + + int returnCode = InternalQuickIO.GetShareEnumResult( targetName, level, ref buffer, ref entriesRead, ref totalEntries, ref resumeHandle ); + + // Available return codes: http://msdn.microsoft.com/en-us/library/windows/desktop/bb525387(v=vs.85).aspx + + if (returnCode == Win32ErrorCodes.ERROR_ACCESS_DENIED) // Access Denied + { + // Admin required, but not granted? try with normal usr + level = QuickIOShareApiReadLevel.Normal; + returnCode = InternalQuickIO.GetShareEnumResult(targetName, level, ref buffer, ref entriesRead, ref totalEntries, ref resumeHandle); + } + + if (returnCode != 0) // we only handle return 0 here + { + yield break; + + } + // Ignore no entries + if (entriesRead <= 0) + { + yield break; + } + + Type shareType = ( level == QuickIOShareApiReadLevel.Admin ) ? typeof( Win32ApiShareInfoAdmin ) : typeof( Win32ApiShareInfoNormal ); + int dataOffset = Marshal.SizeOf( shareType ); + + for (int i = 0, currentDataItem = buffer.ToInt32(); i < entriesRead; i++, currentDataItem += dataOffset) + { + + if (level == QuickIOShareApiReadLevel.Normal) + { + yield return GetShareInfoWithNormalInformation(targetName, new IntPtr(currentDataItem)); + + } + else + { + yield return GetShareInfoWithAdminInformation(targetName, new IntPtr(currentDataItem)); + + } + } + } + finally + { + // Clean up buffer allocated by system + if (buffer != IntPtr.Zero) + { + _ = Win32SafeNativeMethods.NetApiBufferFree(buffer); + } + } + } +} diff --git a/src/QuickIO/QuickIOShare_Enumerate_Async.cs b/src/QuickIO/QuickIOShare_Enumerate_Async.cs new file mode 100644 index 0000000..515b926 --- /dev/null +++ b/src/QuickIO/QuickIOShare_Enumerate_Async.cs @@ -0,0 +1,16 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIOShare +{ + /// + /// Enumerate shares of specific machine. If no machine is specified, local machine is used + /// + /// Collection of + public static Task> EnumerateSharesAsync(string? machineName = null, + QuickIOShareApiReadLevel level = QuickIOShareApiReadLevel.Admin) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateShares(machineName, level)); + } +} diff --git a/src/QuickIO/QuickIOSystemRules.cs b/src/QuickIO/QuickIOSystemRules.cs new file mode 100644 index 0000000..128eae8 --- /dev/null +++ b/src/QuickIO/QuickIOSystemRules.cs @@ -0,0 +1,14 @@ +using System.Text; + +namespace SchwabenCode.QuickIO; + +/// +/// QuickIOSystemRules +/// +internal static class QuickIOSystemRules +{ + /// + /// UTF8Encoding No Emit + /// + public static UTF8Encoding UTF8EncodingNoEmit = new( encoderShouldEmitUTF8Identifier: false ); +} diff --git a/src/QuickIO/QuickIO_Async.cs b/src/QuickIO/QuickIO_Async.cs new file mode 100644 index 0000000..2a303a9 --- /dev/null +++ b/src/QuickIO/QuickIO_Async.cs @@ -0,0 +1,303 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO; + +public static partial class QuickIO +{ + /// + /// Checks whether a file exists + /// + /// File path to check + /// + /// Searched for file but found folder. + /// Path is invalid. + public static Task FileExistsAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => FileExists(path)); + } + + /// + /// Checks whether a file exists + /// + /// File path to check + /// + /// Searched for file but found folder. + /// Path is invalid. + public static Task FileExistsAsync(QuickIOPathInfo pathInfo) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => FileExists(pathInfo)); + } + + /// + /// Checks whether a directory exists + /// + /// Directory path to verify + /// + /// Searched for directory but found file. + /// Path is invalid. + public static Task DirectoryExistsAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => DirectoryExists(path)); + } + + /// + /// Checks whether a directory exists + /// + /// Directory path to verify + /// + /// Searched for directory but found file. + /// Path is invalid. + public static Task DirectoryExistsAsync(QuickIOPathInfo pathInfo) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => DirectoryExists(pathInfo)); + } + + /// + /// Creates a new file. + /// + /// The path to the file. + /// - default + /// - default + /// - default + /// - default 0 (none) + /// The specified path already exists. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + public static Task CreateFileAsync(string path, FileAccess fileAccess = FileAccess.Write, FileShare fileShare = FileShare.None, FileMode fileMode = FileMode.Create, FileAttributes fileAttributes = 0) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => CreateFile(path, fileAccess, fileShare, fileMode, fileAttributes)); + } + + /// + /// Creates a new directory. If is false, the parent directory must exist. + /// + /// The path to the directory. + /// If is false, the parent directory must exist. + /// Path already exists. + /// The directory is not empty. + public static Task CreateDirectoryAsync(string path, bool recursive = false) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => CreateDirectory(path, recursive)); + } + + + /// + /// Removes a file. + /// + /// The path to the file. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// File does not exist. + public static Task DeleteFileAsync(string path) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => DeleteFile(path)); + } + + /// + /// Removes a file. + /// + /// The file. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// File does not exist. + public static Task DeleteFileAsync(QuickIOPathInfo pathInfo) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => DeleteFile(pathInfo)); + } + + + /// + /// Removes a file. + /// + /// The file. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// File does not exist. + public static Task DeleteFileAsync(QuickIOFileInfo file) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => DeleteFile(file)); + } + + /// + /// Removes a directory. + /// + /// The path to the directory. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// The directory is not empty. + public static Task DeleteDirectoryAsync(string path) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => DeleteFile(path)); + } + + /// + /// Removes a directory. + /// + /// The path of the directory. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// The directory is not empty. + public static Task DeleteDirectoryAsync(QuickIOPathInfo pathInfo) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => DeleteFile(pathInfo)); + } + + /// + /// Removes a directory. + /// + /// The directory. + /// One or more intermediate directories do not exist; this function will only create the final directory in the path. + /// The directory is not empty. + public static Task DeleteDirectoryAsync(QuickIODirectoryInfo directoryInfo) + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(() => DeleteDirectory(directoryInfo)); + } + + /// + /// Returns a file list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a file list from the current directory + public static Task> EnumerateFilesAsync(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFiles(path, pattern, searchOption)); + } + + /// + /// Returns a file list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a file list from the current directory + public static Task> EnumerateFilesAsync(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFiles(pathInfo, pattern, searchOption)); + } + + /// + /// Returns a file list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a file list from the current directory + public static Task> EnumerateFilesAsync(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFiles(directoryInfo, pattern, searchOption)); + } + + /// + /// Returns a file path list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a file path list from the current directory + public static Task> EnumerateFilePathsAsync(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFilePaths(path, pattern, searchOption)); + } + + /// + /// Returns a file path list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a file path list from the current directory + public static Task> EnumerateFilePathsAsync(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFilePaths(pathInfo, pattern, searchOption)); + } + + /// + /// Returns a file path list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a file path list from the current directory + public static Task> EnumerateFilePathsAsync(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateFilePaths(directoryInfo, pattern, searchOption)); + } + + /// + /// Returns a directory list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a directory list from the current directory + public static Task> EnumerateDirectoriesAsync(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectories(path, pattern, searchOption)); + } + + /// + /// Returns a directory list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a directory list from the current directory + public static Task> EnumerateDirectoriesAsync(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectories(pathInfo, pattern, searchOption)); + } + + /// + /// Returns a directory list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a directory list from the current directory + public static Task> EnumerateDirectoriesAsync(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectories(directoryInfo, pattern, searchOption)); + } + + /// + /// Returns a directory path list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a directory path list from the current directory + public static Task> EnumerateDirectoryPathsAsync(string path, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectoryPaths(path, pattern, searchOption)); + } + + /// + /// Returns a directory path list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a directory path list from the current directory + public static Task> EnumerateDirectoryPathsAsync(QuickIOPathInfo pathInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectoryPaths(pathInfo, pattern, searchOption)); + } + + /// + /// Returns a directory path list from the current directory using a value to determine whether to search subdirectories. + /// + /// Rootpath + /// Search pattern. Uses Win32 native filtering. + /// One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. + /// Returns a directory path list from the current directory + public static Task> EnumerateDirectoryPathsAsync(QuickIODirectoryInfo directoryInfo, string pattern = QuickIOPatternConstants.All, SearchOption searchOption = SearchOption.TopDirectoryOnly) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => EnumerateDirectoryPaths(directoryInfo, pattern, searchOption)); + } + + /// + /// Receives of specifies path + /// + /// + /// See http://support.microsoft.com/kb/231497 + public static Task GetDiskInformationAsync(string path) + { + return NETCompatibility.AsyncExtensions.GetAsyncResult(() => GetDiskInformation(path)); + } +} diff --git a/src/QuickIO/Transfer/Contracts/IQuickIOTransferJobContract.cs b/src/QuickIO/Transfer/Contracts/IQuickIOTransferJobContract.cs new file mode 100644 index 0000000..3122fb4 --- /dev/null +++ b/src/QuickIO/Transfer/Contracts/IQuickIOTransferJobContract.cs @@ -0,0 +1,29 @@ +using System.ComponentModel; +using System.Diagnostics.Contracts; + +namespace SchwabenCode.QuickIO.Transfer.Contracts; + +/// +/// Contract for +/// +[ContractClass(typeof(IQuickIOTransferJob))] +[Browsable(false)] +[EditorBrowsable(EditorBrowsableState.Never)] +internal abstract class IQuickIOTransferJobContract : IQuickIOTransferJob +{ + public CancellationToken Token { get; private set; } + + public IQuickIOTransferObserver? Observer { get; private set; } + + public int CurrentRetryCount { get; set; } + public int PriorityLevel { get; set; } + public void Run() + { + throw new NotImplementedException(); + } + + public Task RunAsync() + { + return Task.CompletedTask; + } +} diff --git a/src/QuickIO/Transfer/Contracts/IQuickIOTransferObserverContract.cs b/src/QuickIO/Transfer/Contracts/IQuickIOTransferObserverContract.cs new file mode 100644 index 0000000..73b1763 --- /dev/null +++ b/src/QuickIO/Transfer/Contracts/IQuickIOTransferObserverContract.cs @@ -0,0 +1,177 @@ +using System.ComponentModel; +using System.Diagnostics.Contracts; + +namespace SchwabenCode.QuickIO.Transfer.Contracts; + +/// +/// Contract implementation +/// +[ContractClass(typeof(IQuickIOTransferObserver))] +[Browsable(false)] +[EditorBrowsable(EditorBrowsableState.Never)] +public abstract class IQuickIOTransferObserverContract : IQuickIOTransferObserver +{ + public event QuickIOTransferDirectoryCreatingHandler? DirectoryCreating { add { } remove { } } + public event QuickIOTransferDirectoryCreatedHandler? DirectoryCreated { add { } remove { } } + public event QuickIOTransferDirectoryCreationErrorHandler? DirectoryCreationError { add { } remove { } } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnDirectoryCreating(QuickIOTransferDirectoryCreatingEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnDirectoryCreated(QuickIOTransferDirectoryCreatedEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnDirectoryCreationError(QuickIOTransferDirectoryCreationErrorEventArgs args) { } + + public event QuickIOTransferFileCreationErrorHandler? FileCreationError { add { } remove { } } + public event QuickIOTransferFileCreationStartedHandler? FileCreationStarted { add { } remove { } } + public event QuickIOTransferFileCreationFinishedHandler? FileCreationFinished { add { } remove { } } + public event QuickIOTransferFileCreationProgressHandler? FileCreationProgress { add { } remove { } } + public void OnFileCreationError(QuickIOTransferFileCreationErrorEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnFileCreationProgress(QuickIOTransferFileCreationProgressEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnFileCreationStarted(QuickIOTransferFileCreationStartedEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnFileCreationFinished(QuickIOTransferFileCreationFinishedEventArgs args) { } + + public event QuickIOTransferFileCopyErrorHandler? FileCopyError { add { } remove { } } + public event QuickIOTransferFileCopyProgressHandler? FileCopyProgress { add { } remove { } } + public event QuickIOTransferFileCopyStartedHandler? FileCopyStarted { add { } remove { } } + public event QuickIOTransferFileCopyFinishedHandler? FileCopyFinished { add { } remove { } } + public void OnFileCopyError(QuickIOTransferFileCopyErrorEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnFileCopyProgress(QuickIOTransferFileCopyProgressEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnFileCopyStarted(QuickIOTransferFileCopyStartedEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnFileCopyFinished(QuickIOTransferFileCopyFinishedEventArgs args) { } + + public event QuickIOTransferCompletedAddingRequestedHandler? CompletedAddingRequested { add { } remove { } } + public event QuickIOTransferCancellationRequestedHandler? CancellationRequested { add { } remove { } } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnCompletedAddingRequested(EventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnCancellationRequested(EventArgs args) { } + + public event QuickIOTransferWorkerIsWaitingHandler? WorkerIsWaiting { add { } remove { } } + public event QuickIOTransferWorkerWokeUpHandler? WorkerWokeUp { add { } remove { } } + public event QuickIOTransferWorkerPickedJobHandler? WorkerPickedJob { add { } remove { } } + public event QuickIOTransferWorkerCreatedHandler? WorkerCreated { add { } remove { } } + public event QuickIOTransferWorkerStartedHandler? WorkerStarted { add { } remove { } } + public event QuickIOTransferWorkerShutdownHandler? WorkerShutdown { add { } remove { } } + public void OnWorkerWokeUp(QuickIOTransferWorkerWokeUpEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnWorkerIsWaiting(QuickIOTransferWorkerIsSleepingEventArgs args) { } + + public void OnWorkerPickedJob(QuickIOTransferWorkerPickedJobEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnWorkerCreated(QuickIOTransferWorkerCreatedEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnWorkerStarted(QuickIOTransferWorkerStartedEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnWorkerShutdown(QuickIOTransferWorkerShutdownEventArgs args) { } + + public event QuickIOTransferJobRunHandler? JobRun { add { } remove { } } + public event QuickIOTransferJobErrorHandler? JobError { add { } remove { } } + public event QuickIOTransferJobEndHandler? JobEnd { add { } remove { } } + public event QuickIOTransferJobEnqueuedHandler? JobEnqueued { add { } remove { } } + public event QuickIOTransferJobDequeuedHandler? JobDequeued { add { } remove { } } + public event QuickIOTransferJobRequeuedHandler? JobRequeued { add { } remove { } } + public event QuickIOTransferJobRetryMaxReachedHandler? JobRetryMaxReached { add { } remove { } } + public void OnJobRun(QuickIOTransferJobRunEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnJobError(QuickIOTransferJobErrorEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnJobEnd(QuickIOTransferJobEndEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnJobEnqueued(QuickIOTransferJobEnqueuedEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnJobDequeued(QuickIOTransferJobDequeuedEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnJobRequeued(QuickIOTransferJobRequeuedEventArgs args) { } + + /// + /// Contract implementation + /// + /// Cannot be null + public void OnJobRetryMaxReached(QuickIOTransferJobReatryMaxReachedEventArgs args) { } +} diff --git a/src/QuickIO/Transfer/Contracts/IQuickIOTransferWriteJobContract.cs b/src/QuickIO/Transfer/Contracts/IQuickIOTransferWriteJobContract.cs new file mode 100644 index 0000000..a556af8 --- /dev/null +++ b/src/QuickIO/Transfer/Contracts/IQuickIOTransferWriteJobContract.cs @@ -0,0 +1,32 @@ +using System.ComponentModel; +using System.Diagnostics.Contracts; + +namespace SchwabenCode.QuickIO.Transfer.Contracts; + +/// +/// Contract implementation +/// +[ContractClass(typeof(IQuickIOTransferObserver))] +[Browsable(false)] +[EditorBrowsable(EditorBrowsableState.Never)] +public abstract class IQuickIOTransferWriteJobContract : IQuickIOTransferWriteJob +{ + public CancellationToken Token { get; private set; } + public IQuickIOTransferObserver? Observer { get; private set; } + + public int CurrentRetryCount { get; set; } + public int PriorityLevel { get; set; } + public void Run() + { + throw new NotImplementedException(); + } + + public Task RunAsync() + { + return Task.CompletedTask; + } + + public int MaxBufferSize { get; set; } + public bool ParentExistanceCheck { get; private set; } + public bool Overwrite { get; set; } +} diff --git a/src/QuickIO/Transfer/IQuickIOTransferJob.cs b/src/QuickIO/Transfer/IQuickIOTransferJob.cs new file mode 100644 index 0000000..90a257c --- /dev/null +++ b/src/QuickIO/Transfer/IQuickIOTransferJob.cs @@ -0,0 +1,41 @@ +using System.Diagnostics.Contracts; +using SchwabenCode.QuickIO.Transfer.Contracts; + +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Interface for transfer jobs +/// +[ContractClass(typeof(IQuickIOTransferJobContract))] +public interface IQuickIOTransferJob +{ + /// + /// Cancellation Token + /// + CancellationToken Token { get; } + + /// + /// Observer for Condition Monitoring + /// + IQuickIOTransferObserver? Observer { get; } + + /// + /// Retry count before firing broken exception + /// + int CurrentRetryCount { get; set; } + + /// + /// Prority level. Higher priority = higher value. 0 = default + /// + int PriorityLevel { get; set; } + + /// + /// Run implementation + /// + void Run(); + + /// + /// Executes in Async context + /// + Task RunAsync(); +} diff --git a/src/QuickIO/Transfer/IQuickIOTransferObserver.cs b/src/QuickIO/Transfer/IQuickIOTransferObserver.cs new file mode 100644 index 0000000..8503c8c --- /dev/null +++ b/src/QuickIO/Transfer/IQuickIOTransferObserver.cs @@ -0,0 +1,299 @@ +using System.Diagnostics.Contracts; +using SchwabenCode.QuickIO.Transfer.Contracts; + +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Implementation requirements for central observer. +/// +/// See for custom observer implementation example. +[ContractClass(typeof(IQuickIOTransferObserverContract))] +public interface IQuickIOTransferObserver +{ + /// + /// This event is raised before an upcoming directory creation operation is performed + /// + event QuickIOTransferDirectoryCreatingHandler? DirectoryCreating; + + /// + /// This event is raised when a directory was created + /// + event QuickIOTransferDirectoryCreatedHandler? DirectoryCreated; + + /// + /// This event is raised if directory creation operation fails + /// + event QuickIOTransferDirectoryCreationErrorHandler? DirectoryCreationError; + + /// + /// Fire + /// + /// Holds further event information + void OnDirectoryCreating(QuickIOTransferDirectoryCreatingEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnDirectoryCreated(QuickIOTransferDirectoryCreatedEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnDirectoryCreationError(QuickIOTransferDirectoryCreationErrorEventArgs args); + + + /// + /// This event is raised if file creation fails + /// + event QuickIOTransferFileCreationErrorHandler? FileCreationError; + + /// + /// This event is triggered at the beginning of the file copy operation. + /// + event QuickIOTransferFileCreationStartedHandler? FileCreationStarted; + + /// + /// This event is raised at the end of the file copy operation. + /// + event QuickIOTransferFileCreationFinishedHandler? FileCreationFinished; + + /// + /// This event is raised at the end of the file copy operation. + /// + event QuickIOTransferFileCreationProgressHandler? FileCreationProgress; + + /// + /// Fire + /// + /// Holds further event information + void OnFileCreationError(QuickIOTransferFileCreationErrorEventArgs args); + /// + /// Fire + /// + /// Holds further event information + void OnFileCreationProgress(QuickIOTransferFileCreationProgressEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnFileCreationStarted(QuickIOTransferFileCreationStartedEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnFileCreationFinished(QuickIOTransferFileCreationFinishedEventArgs args); + + /// + /// This event is raised if file copy operation fails + /// + event QuickIOTransferFileCopyErrorHandler? FileCopyError; + + /// + /// This event is raised during a copy of a file. It provides current information such as progress, speed and estimated time. + /// + event QuickIOTransferFileCopyProgressHandler? FileCopyProgress; + + /// + /// This event is triggered at the beginning of the file copy operation. + /// + event QuickIOTransferFileCopyStartedHandler? FileCopyStarted; + + /// + /// This event is raised at the end of the file copy operation. + /// + event QuickIOTransferFileCopyFinishedHandler? FileCopyFinished; + + /// + /// Fire + /// + /// Holds further event information + void OnFileCopyError(QuickIOTransferFileCopyErrorEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnFileCopyProgress(QuickIOTransferFileCopyProgressEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnFileCopyStarted(QuickIOTransferFileCopyStartedEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnFileCopyFinished(QuickIOTransferFileCopyFinishedEventArgs args); + + /// + /// This event is raised if the service has been made known that no new elements will be added. + /// + event QuickIOTransferCompletedAddingRequestedHandler? CompletedAddingRequested; + + /// + /// This event is raised if the service has been made known that he should cancel the processing + /// + event QuickIOTransferCancellationRequestedHandler? CancellationRequested; + + /// + /// Fire + /// + /// Holds further event information + void OnCompletedAddingRequested(EventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnCancellationRequested(EventArgs args); + + /// + /// This event is raised when a processing thread is waiting for new items + /// + event QuickIOTransferWorkerIsWaitingHandler? WorkerIsWaiting; + + /// + /// This event is raised when a processing thread, which so far has been waiting for, was notified of a new item in the queue. + /// It may be that he gets no element from the queue, because another thread was faster. He would sleep lie down again, if no more items available. + /// + event QuickIOTransferWorkerWokeUpHandler? WorkerWokeUp; + + /// + /// This event is raised when a processing thread has taken a new item from the queue + /// + event QuickIOTransferWorkerPickedJobHandler? WorkerPickedJob; + + /// + /// This event is raised when a new processing thread was created + /// + event QuickIOTransferWorkerCreatedHandler? WorkerCreated; + + /// + /// This event is raised when a processing thread started + /// + event QuickIOTransferWorkerStartedHandler? WorkerStarted; + + /// + /// This event is raised when a processing thread was shutdown + /// + event QuickIOTransferWorkerShutdownHandler? WorkerShutdown; + + /// + /// Fire + /// + /// Holds further event information + void OnWorkerWokeUp(QuickIOTransferWorkerWokeUpEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnWorkerIsWaiting(QuickIOTransferWorkerIsSleepingEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnWorkerPickedJob(QuickIOTransferWorkerPickedJobEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnWorkerCreated(QuickIOTransferWorkerCreatedEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnWorkerStarted(QuickIOTransferWorkerStartedEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnWorkerShutdown(QuickIOTransferWorkerShutdownEventArgs args); + + /// + /// This event is raised when is called + /// + event QuickIOTransferJobRunHandler? JobRun; + + /// + /// This event is triggered if has an error + /// + event QuickIOTransferJobErrorHandler? JobError; + + /// + /// This event is raised at the end + /// + event QuickIOTransferJobEndHandler? JobEnd; + + /// + /// This event is raised if the job of a queue has been added. + /// + event QuickIOTransferJobEnqueuedHandler? JobEnqueued; + + /// + /// This event is raised if the job was taken from of a queue. + /// + event QuickIOTransferJobDequeuedHandler? JobDequeued; + + /// + /// This event is raised if the job was re-added to a queue. + /// + event QuickIOTransferJobRequeuedHandler? JobRequeued; + + /// + /// This event is raised if the max retry count is reached. + /// + event QuickIOTransferJobRetryMaxReachedHandler JobRetryMaxReached; + + /// + /// Fire + /// + /// Holds further event information + void OnJobRun(QuickIOTransferJobRunEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnJobError(QuickIOTransferJobErrorEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnJobEnd(QuickIOTransferJobEndEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnJobEnqueued(QuickIOTransferJobEnqueuedEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnJobDequeued(QuickIOTransferJobDequeuedEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnJobRequeued(QuickIOTransferJobRequeuedEventArgs args); + + /// + /// Fire + /// + /// Holds further event information + void OnJobRetryMaxReached(QuickIOTransferJobReatryMaxReachedEventArgs args); +} diff --git a/src/QuickIO/Transfer/IQuickIOTransferWriteJob.cs b/src/QuickIO/Transfer/IQuickIOTransferWriteJob.cs new file mode 100644 index 0000000..12e1356 --- /dev/null +++ b/src/QuickIO/Transfer/IQuickIOTransferWriteJob.cs @@ -0,0 +1,26 @@ +using System.Diagnostics.Contracts; +using SchwabenCode.QuickIO.Transfer.Contracts; + +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Implements with Overwrite option +/// +[ContractClass(typeof(IQuickIOTransferWriteJobContract))] +public interface IQuickIOTransferWriteJob : IQuickIOTransferJob +{ + /// + /// Max Buffer Size for Transfer + /// + int MaxBufferSize { get; set; } + + /// + /// True to check parent folder existance. False is much faster, but you have to be sure that the parent exists. + /// + bool ParentExistanceCheck { get; } + + /// + /// true to overwrite existing element + /// + bool Overwrite { get; set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferBackgroundService.cs b/src/QuickIO/Transfer/QuickIOTransferBackgroundService.cs new file mode 100644 index 0000000..54794aa --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferBackgroundService.cs @@ -0,0 +1,228 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Instance for the continuous transfer of files; for example as a service. +/// +/// +/// Sort incoming files by an always watching file service +/// +/// +/// +/// /// worker started +/// /// +/// private static void OnServiceWorkerStarted( object sender, QuickIOTransferWorkerStartedEventArgs e ) +/// { +/// Console.WriteLine( "[!] Worker Started. ID: " + e.WorkerID ); +/// } +/// +/// /// +/// /// new worker +/// /// +/// static void OnServiceWorkerCreated( object sender, QuickIOTransferWorkerCreatedEventArgs e ) +/// { +/// Console.WriteLine( "[!] New Worker. ID: " + e.WorkerID ); +/// } +/// +/// /// +/// /// worker catched a job +/// /// +/// static void OnServiceWorkerPickedJob( object sender, QuickIOTransferWorkerPickedJobEventArgs e ) +/// { +/// Console.WriteLine( "[!] Worker ID# " + e.WorkerID + " picked job: " + e.GetType( ) ); +/// } +/// +/// /// +/// /// job was broken by an exception, but requred +/// /// +/// static void JobRequeued( object sender, QuickIOTransferJobRequeuedArgs e ) +/// { +/// Console.WriteLine( "[JOB REQUEUED] Try: #" + e.Job.CurrentRetryCount + " - " + e.Job.GetType( ) + " failed: " + e.Exception.Message ); +/// } +/// +/// /// +/// /// Report of job was taken from queue +/// /// +/// static void OnJobDequeued( object sender, QuickIOTransferJobDequeuedArgs e ) +/// { +/// Console.WriteLine( "[JOB DEQUEUED] " + e.Job.GetType( ) ); +/// } +/// +/// /// +/// /// Report for new jobs +/// /// +/// static void OnJobEnqueued( object sender, QuickIOTransferJobEnqueuedArgs e ) +/// { +/// Console.WriteLine( "[NEW JOB] " + e.Job.GetType( ) ); +/// } +/// +/// /// +/// /// Progress Report +/// /// +/// static void OnFileCopyStarted( object sender, QuickIOTransferFileCopyStartedArgs args ) +/// { +/// Console.WriteLine( ">>>>>> STARTED " + args.SourcePath + " to " + args.TargetPath ); +/// } +/// +/// /// +/// /// Progress Report +/// /// +/// static void OnFileCopyFinished( object sender, QuickIOTransferFileCopyFinishedArgs args ) +/// { +/// Console.WriteLine( ">>>>>> FINISHED " + args.SourcePath + " to " + args.TargetPath + " - MB/s: " + ( args.BytesPerSecond / 1024.0 / 1024.0 ).ToString( "0.0" ) ); +/// } +/// /// +/// /// Progress Report +/// /// +/// static void OnFileCopyProgress( object sender, QuickIOTransferFileCopyProgressArgs args ) +/// { +/// Console.WriteLine( "Transfering " + args.SourcePath + " to " + args.TargetPath + " - %: " + args.Percentage + " MB/s: " + ( args.BytesPerSecond / 1024.0 / 1024.0 ).ToString( "0.0" ) ); +/// } +/// +/// /// +/// /// Copy movie file from drop folder to internal movie folder +/// /// +/// static void OnCreated_MovieFile( object sender, FileSystemEventArgs e ) +/// { +/// var queueItem = new QuickIOTransferFileCopyJob( e.FullPath, movieFolder, overwrite: true ); +/// TransferBackgroundService.Add( queueItem ); +/// } +/// +/// /// +/// /// Copy picture file from drop folder to internal picture folder +/// /// +/// static void OnCreated_Picture( object sender, FileSystemEventArgs e ) +/// { +/// var queueItem = new QuickIOTransferFileCopyJob( e.FullPath, pictureFolder, overwrite: true, parentExistanceCheck: false ); +/// TransferBackgroundService.Add( queueItem ); +/// } +/// } +/// ]]> +/// +public class QuickIOTransferBackgroundService : QuickIOTransferServiceBase +{ + /// + /// Creates an instance for with default observer + /// + /// + /// + /// true to auto start. false to start service by using + public QuickIOTransferBackgroundService(int workerCount, int maxFileRetry = 3, bool autostart = true) + : this(null, workerCount, maxFileRetry) + { + if (autostart) + { + _ = Start(); + } + } + + /// + /// Creates an instance for with specified observer + /// + /// Observer for monitoring + /// + /// + /// true to auto start. false to start service by using + public QuickIOTransferBackgroundService(IQuickIOTransferObserver? observer, int workerCount, int maxFileRetry = 3, + bool autostart = true) : base(observer, workerCount, maxFileRetry) + { + if (autostart) + { + _ = Start(); + } + } + + /// + /// Starts the service if not started yet + /// + public bool Start() + { + return StartWorking(); + } + + /// + /// Adds an item to the queue. null will not be insered and returns false. + /// If is called the return value is false, too + /// + /// Item to add + /// true on add; false if not + public void Add(QuickIOTransferFileCopyJob queueItem) + { + if (CancelRequested) + { + throw new Exception("Queue is cancelled."); + } + + if (AddingCompleted) + { + throw new Exception("Adding is completed."); + } + + InternalAdd(queueItem); + } + + /// + /// Adds a new worker to the service. Worker will be created and started instantly. + /// + /// Must be 1 or greater + /// It's not recommended to use more workers than the count of useable CPU cores. + public new void AddWorker(int count = 1) + { + base.AddWorker(count); + } + + /// + /// Remove workers from the service. + /// + /// Must be 1 or greater + public new void RemoveWorker(int count = 1) + { + base.RemoveWorker(count); + } + + /// + /// Joins all threads and blocks until all threads and queue items are completed. + /// Queue has to be completed. + /// + public new void WaitForFinish() + { + base.WaitForFinish(); + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferDirectoryCopyService.cs b/src/QuickIO/Transfer/QuickIOTransferDirectoryCopyService.cs new file mode 100644 index 0000000..9295649 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferDirectoryCopyService.cs @@ -0,0 +1,346 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Copy directory with progress monitoring +/// +/// +/// Copy complete directory +/// +/// +/// +/// +public partial class QuickIOTransferDirectoryCopyService : QuickIOTransferServiceBase +{ + /// + /// Directory to copy + /// + public QuickIODirectoryInfo SourceDirectoryInfo { get; private set; } + + /// + /// Target fullname + /// + public string TargetFullName { get; private set; } + + /// + /// Deepth to copy + /// + public SearchOption SearchOption { get; set; } + + /// + /// true to overwrite existing content + /// + public bool Overwrite { get; set; } + + /// + /// Creates new instance of with default observer + /// + /// Directory to copy + /// Target fullname + /// Copy Worker Counts. Use 1 on local systems. Use >2 with SMB shares + /// Count of retries before copy is broken + /// of deepth to copy + /// true to overwrite existing files + /// + /// Copy complete directory + /// + /// + /// + /// + public QuickIOTransferDirectoryCopyService(QuickIODirectoryInfo sourceDirectoryInfo, string targetFullName, int threadCount = 1, int retryCount = 3, SearchOption searchOption = SearchOption.TopDirectoryOnly, bool overwrite = false) + : this(null, sourceDirectoryInfo, targetFullName, threadCount, retryCount, searchOption, overwrite) + { + } + + /// + /// Creates new instance of with specified observer + /// + /// Observer + /// Directory to copy + /// Target fullname + /// Copy Worker Counts. Use 1 on local systems. Use >2 with SMB shares + /// Count of retries before copy is broken + /// of deepth to copy + /// true to overwrite existing files + /// + /// Copy complete directory + /// + /// + /// + /// + public QuickIOTransferDirectoryCopyService(IQuickIOTransferObserver? observer, QuickIODirectoryInfo sourceDirectoryInfo, string targetFullName, int threadCount = 1, int retryCount = 3, SearchOption searchOption = SearchOption.TopDirectoryOnly, bool overwrite = false) + : base(observer, threadCount, retryCount) + { + SourceDirectoryInfo = sourceDirectoryInfo; + TargetFullName = targetFullName; + SearchOption = searchOption; + Overwrite = overwrite; + + // Register Events + RegisterInternalEventHandling(); + + _ = StartWorking(); + } + + /// + /// thread safe indicator if copy is running + /// + private volatile bool _running; + + /// + /// true if copy process is running + /// + public bool IsRunning + { + get { return _running; } + protected set { _running = value; } + } + + /// + /// Starts the copy process. + /// First it determines all content information of source. Then the target directory structure will be created before transfer begins + /// + public void Start() + { + try + { + if (IsRunning) + { + throw new Exception("Already running."); + } + + // Load prefences + InternalDirectoryTransferPrefences preferences = DetermineDirectoryTransferPrefences( SourceDirectoryInfo, TargetFullName, SearchOption, Overwrite ); + + InternalAddRange(preferences.CreateDirectoryJobs); + InternalAddRange(preferences.FileTransferQueueItems); + + // No more will be added + CompleteAdding(); + + // Wait for finish + WaitForFinish(); + } + finally + { + IsRunning = false; + } + } + + /// + /// Starts the copy process as task. + /// First it determines all content information of source. Then the target directory structure will be created before transfer begins + /// + public Task StartAsync() + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(Start); + } + + private class InternalDirectoryTransferPrefences + { + public List CreateDirectoryJobs { get; set; } = []; + public List FileTransferQueueItems { get; set; } = []; + } + + private InternalDirectoryTransferPrefences DetermineDirectoryTransferPrefences(QuickIODirectoryInfo sourceDirectoryInfo, string targetFullName, SearchOption searchOption, bool overwrite) + { + InternalDirectoryTransferPrefences prefences = new( ); + + IEnumerable> allContentUncPaths = QuickIODirectory.EnumerateFileSystemEntryPaths( sourceDirectoryInfo, QuickIOPatternConstants.All, searchOption, QuickIOPathType.UNC ); + + QuickIOPathInfo targetPathInfo = new( targetFullName ); + + prefences.CreateDirectoryJobs = []; + prefences.FileTransferQueueItems = []; + foreach (KeyValuePair entry in allContentUncPaths) + { + string target = targetPathInfo.FullNameUnc + entry.Key.Substring( sourceDirectoryInfo.FullNameUnc.Length ); + + switch (entry.Value) + { + case QuickIOFileSystemEntryType.Directory: + { + prefences.CreateDirectoryJobs.Add(new QuickIOTransferDirectoryCreationJob(target)); + } + break; + + case QuickIOFileSystemEntryType.File: + { + prefences.FileTransferQueueItems.Add(new QuickIOTransferFileCopyJob(entry.Key, target, MaxBufferSize, overwrite, false)); + } + break; + } + } + + return prefences; + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferDirectoryCopyService_Events.cs b/src/QuickIO/Transfer/QuickIOTransferDirectoryCopyService_Events.cs new file mode 100644 index 0000000..0fcc4da --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferDirectoryCopyService_Events.cs @@ -0,0 +1,123 @@ +namespace SchwabenCode.QuickIO.Transfer; + +public partial class QuickIOTransferDirectoryCopyService +{ + /// + /// Copy events from observer to current instance + /// + private void RegisterInternalEventHandling() + { + Observer.FileCopyError += (sender, e) => OnFileCopyError(e); + Observer.FileCopyFinished += (sender, e) => OnFileCopyFinished(e); + Observer.FileCopyProgress += (sender, e) => OnFileCopyProgress(e); + Observer.FileCopyStarted += (sender, e) => OnFileCopyStarted(e); + + Observer.DirectoryCreated += (sender, e) => OnDirectoryCreated(e); + Observer.DirectoryCreating += (sender, e) => OnDirectoryCreating(e); + Observer.DirectoryCreationError += (sender, e) => OnDirectoryCreationError(e); + } + + #region Directory Create + + /// + /// This event is raised if directory creation operation fails + /// + public event QuickIOTransferDirectoryCreationErrorHandler? DirectoryCreationError; + + /// + /// This event is raised before an upcoming directory creation operation is performed + /// + public event QuickIOTransferDirectoryCreatingHandler? DirectoryCreating; + + /// + /// This event is raised when a directory was created + /// + public event QuickIOTransferDirectoryCreatedHandler? DirectoryCreated; + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnDirectoryCreationError(QuickIOTransferDirectoryCreationErrorEventArgs args) + { + DirectoryCreationError?.Invoke(this, args); + } + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnDirectoryCreating(QuickIOTransferDirectoryCreatingEventArgs args) + { + DirectoryCreating?.Invoke(this, args); + } + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnDirectoryCreated(QuickIOTransferDirectoryCreatedEventArgs args) + { + DirectoryCreated?.Invoke(this, args); + } + + #endregion + #region File Copy + + /// + /// This event is raised if file copy operation fails + /// + public event QuickIOTransferFileCopyErrorHandler? FileCopyError; + + /// + /// This event is raised during a copy of a file. It provides current information such as progress, speed and estimated time. + /// + public event QuickIOTransferFileCopyProgressHandler? FileCopyProgress; + + /// + /// This event is triggered at the beginning of the file copy operation. + /// + public event QuickIOTransferFileCopyStartedHandler? FileCopyStarted; + + /// + /// This event is raised at the end of the file copy operation. + /// + public event QuickIOTransferFileCopyFinishedHandler? FileCopyFinished; + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCopyError(QuickIOTransferFileCopyErrorEventArgs args) + { + FileCopyError?.Invoke(this, args); + } + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCopyProgress(QuickIOTransferFileCopyProgressEventArgs args) + { + FileCopyProgress?.Invoke(this, args); + } + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCopyStarted(QuickIOTransferFileCopyStartedEventArgs args) + { + FileCopyStarted?.Invoke(this, args); + } + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCopyFinished(QuickIOTransferFileCopyFinishedEventArgs args) + { + FileCopyFinished?.Invoke(this, args); + } + #endregion +} diff --git a/src/QuickIO/Transfer/QuickIOTransferDirectoryCreatedEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferDirectoryCreatedEventArgs.cs new file mode 100644 index 0000000..1d9818c --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferDirectoryCreatedEventArgs.cs @@ -0,0 +1,23 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information after a directory create operation was performed +/// +public class QuickIOTransferDirectoryCreatedEventArgs : QuickIOTransferJobEventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected job + /// Directory fullname that was created + public QuickIOTransferDirectoryCreatedEventArgs(IQuickIOTransferJob job, string targetPath) + : base(job) + { + TargetPath = targetPath; + } + + /// + /// Target path + /// + public string TargetPath { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferDirectoryCreatingEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferDirectoryCreatingEventArgs.cs new file mode 100644 index 0000000..a88eb19 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferDirectoryCreatingEventArgs.cs @@ -0,0 +1,23 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information of an upcoming directory creation operation +/// +public class QuickIOTransferDirectoryCreatingEventArgs : QuickIOTransferJobEventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected job + /// Directory fullname to create + public QuickIOTransferDirectoryCreatingEventArgs(IQuickIOTransferJob job, string targetPath) + : base(job) + { + TargetPath = targetPath; + } + + /// + /// Target file path + /// + public string TargetPath { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferDirectoryCreationErrorEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferDirectoryCreationErrorEventArgs.cs new file mode 100644 index 0000000..074579c --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferDirectoryCreationErrorEventArgs.cs @@ -0,0 +1,24 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains further information when a directory creation process fails +/// +public class QuickIOTransferDirectoryCreationErrorEventArgs : QuickIOTransferJobWriteEventArgs +{ + /// + /// Exception + /// + public Exception Exception { get; private set; } + + /// + /// Creates new instance of + /// + /// Affected job + /// Target path + /// Exception + public QuickIOTransferDirectoryCreationErrorEventArgs(IQuickIOTransferJob job, string target, Exception e) + : base(job, target) + { + Exception = e; + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferDirectoryCreationJob.cs b/src/QuickIO/Transfer/QuickIOTransferDirectoryCreationJob.cs new file mode 100644 index 0000000..b5bbccc --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferDirectoryCreationJob.cs @@ -0,0 +1,193 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Job for creating directories +/// +/// +/// Directory Creation job with observer +/// +/// +/// +/// +/// Directory Creation job +/// +/// +/// +/// +/// Event definitions for this example +/// +/// +/// +/// +/// +public class QuickIOTransferDirectoryCreationJob : QuickIOTransferJob +{ + /// + /// Creates the directory + /// + protected override void Implementation() + { + OnDirectoryCreating(); + + if (!QuickIODirectory.Exists(DirectoryToCreatePath)) + { + QuickIODirectory.Create(DirectoryToCreatePath, true); + } + + OnDirectoryCreated(); + } + + /// + /// Directory fullname to create + /// + public string DirectoryToCreatePath { get; private set; } + + /// + /// Job for creating directories with default observer + /// + /// Directory fullname to create + /// true to overwrite + /// Priority level of directory creation should be higher than file creation without parent check + public QuickIOTransferDirectoryCreationJob(string directoryToCreatePath, bool overwrite = true, int prorityLevel = 1) + : this(null, directoryToCreatePath, overwrite, prorityLevel) + { + } + + /// + /// Job for creating directories with default observer + /// + /// Observer + /// Directory fullname to create + /// true to overwrite + /// Priority level of directory creation should be higher than file creation without parent check + public QuickIOTransferDirectoryCreationJob(IQuickIOTransferObserver? observer, string directoryToCreatePath, bool overwrite = true, int prorityLevel = 1) + : base(observer, prorityLevel) + { + DirectoryToCreatePath = directoryToCreatePath; + } + + #region Events + /// + /// This event is raised if directory creation operation fails + /// + public new event QuickIOTransferDirectoryCreationErrorHandler? Error; + + /// + /// This event is raised before an upcoming directory creation operation is performed + /// + public event QuickIOTransferDirectoryCreatingHandler? DirectoryCreating; + + /// + /// This event is raised when a directory was created + /// + public event QuickIOTransferDirectoryCreatedHandler? DirectoryCreated; + + /// + /// Fire + /// + private void OnDirectoryCreating() + { + OnDirectoryCreating(DirectoryToCreatePath); + } + /// + /// Fires + /// + private void OnDirectoryCreated() + { + OnDirectoryCreated(DirectoryToCreatePath); + } + + + /// + /// Fires + /// + /// + protected override void OnError(Exception e) + { + // base throw not important + //base.OnError( e ); + + QuickIOTransferDirectoryCreationErrorEventArgs? args = null; + if (Error != null) + { + args = new QuickIOTransferDirectoryCreationErrorEventArgs(this, DirectoryToCreatePath, e); + Error(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferDirectoryCreationErrorEventArgs(this, DirectoryToCreatePath, e); + Observer.OnDirectoryCreationError(args); + } + } + /// + /// Fire + /// + private void OnDirectoryCreating(string directoryPath) + { + QuickIOTransferDirectoryCreatingEventArgs? args = null; + if (DirectoryCreating != null) + { + args = new QuickIOTransferDirectoryCreatingEventArgs(this, directoryPath); + DirectoryCreating(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferDirectoryCreatingEventArgs(this, directoryPath); + Observer.OnDirectoryCreating(args); + } + } + + + /// + /// Fires + /// + private void OnDirectoryCreated(string directoryPath) + { + QuickIOTransferDirectoryCreatedEventArgs? args = null; + if (DirectoryCreated != null) + { + args = new QuickIOTransferDirectoryCreatedEventArgs(this, directoryPath); + DirectoryCreated(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferDirectoryCreatedEventArgs(this, directoryPath); + Observer.OnDirectoryCreated(args); + } + } + #endregion +} diff --git a/src/QuickIO/Transfer/QuickIOTransferEventDelegates.cs b/src/QuickIO/Transfer/QuickIOTransferEventDelegates.cs new file mode 100644 index 0000000..a45f334 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferEventDelegates.cs @@ -0,0 +1,200 @@ +namespace SchwabenCode.QuickIO.Transfer; + +#region Job Delegates +/// +/// This event is raised when a job runs +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferJobRunHandler(object sender, QuickIOTransferJobRunEventArgs e); +/// +/// This event is raised when a job got an error +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferJobErrorHandler(object sender, QuickIOTransferJobErrorEventArgs e); +/// +/// This event is raised when a job ends +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferJobEndHandler(object sender, QuickIOTransferJobEndEventArgs e); + +/// +/// This event is raised when a new job to the queue is added to +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferJobEnqueuedHandler(object sender, QuickIOTransferJobEnqueuedEventArgs e); + +/// +/// This event is raised when a job was taken from the queue +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferJobDequeuedHandler(object sender, QuickIOTransferJobDequeuedEventArgs e); + + +/// +/// This event is raised when a job was taken from the queue, whose type is unknown. This job can not be processed and will be discarded. +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferUnknownJobHandler(object sender, QuickIOTransferJobEnqueuedEventArgs e); + + +/// +/// This event is raised when a job triggered an error during processing. It will be re-added to the queue. +/// It will be re-added to the queue if the maximum number of attempts +/// MaxJobRetryAttempts +/// +/// is not reached. +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferJobRequeuedHandler(object sender, QuickIOTransferJobRequeuedEventArgs e); + + +/// +/// Max +/// MaxJobRetryAttempts +/// +/// of a job reached +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferJobRetryMaxReachedHandler(object sender, QuickIOTransferJobReatryMaxReachedEventArgs e); +#endregion + +#region FileCreation Delegates + +/// +/// This event is raised during a Creation of a file. It provides current information such as progress, speed and estimated time. +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferFileCreationProgressHandler(object sender, QuickIOTransferFileCreationProgressEventArgs e); +/// +/// This event is raised if a file creation fails +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferFileCreationErrorHandler(object sender, QuickIOTransferFileCreationErrorEventArgs e); +/// +/// This event is triggered at the beginning of the file Creation operation. +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferFileCreationStartedHandler(object sender, QuickIOTransferFileCreationStartedEventArgs e); +/// +/// This event is raised at the end of the file Creation operation. +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferFileCreationFinishedHandler(object sender, QuickIOTransferFileCreationFinishedEventArgs e); + +#endregion + +#region File Copy + +/// +/// This event is raised during a copy of a file. It provides current information such as progress, speed and estimated time. +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferFileCopyProgressHandler(object sender, QuickIOTransferFileCopyProgressEventArgs e); +/// +/// This event is raised if a file copy fails +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferFileCopyErrorHandler(object sender, QuickIOTransferFileCopyErrorEventArgs e); +/// +/// This event is triggered at the beginning of the file copy operation. +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferFileCopyStartedHandler(object sender, QuickIOTransferFileCopyStartedEventArgs e); +/// +/// This event is raised at the end of the file copy operation. +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferFileCopyFinishedHandler(object sender, QuickIOTransferFileCopyFinishedEventArgs e); +#endregion + +#region Directory +/// +/// This event is raised if a directoy creation fails +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferDirectoryCreationErrorHandler(object sender, QuickIOTransferDirectoryCreationErrorEventArgs e); +/// +/// This event is raised before an upcoming directory creation operation is performed +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferDirectoryCreatingHandler(object sender, QuickIOTransferDirectoryCreatingEventArgs e); +/// +/// This event is raised when a directory was created +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferDirectoryCreatedHandler(object sender, QuickIOTransferDirectoryCreatedEventArgs e); +#endregion + +#region Service +/// +/// This event is raised if the service has been made known that no new elements will be added. +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferCompletedAddingRequestedHandler(object sender, EventArgs e); +/// +/// This event is raised if the service has been made known that he should cancel the processing +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferCancellationRequestedHandler(object sender, EventArgs e); +#endregion + +#region Workers +/// +/// This event is raised when a processing thread is waiting for new items +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferWorkerIsWaitingHandler(object sender, QuickIOTransferWorkerIsSleepingEventArgs e); +/// +/// This event is raised when a processing thread, which so far has been waiting for, was notified of a new item in the queue. +/// It may be that he gets no element from the queue, because another thread was faster. He would sleep lie down again, if no more items available. +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferWorkerWokeUpHandler(object sender, QuickIOTransferWorkerWokeUpEventArgs e); +/// +/// This event is raised when a processing thread has taken a new item from the queue +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferWorkerPickedJobHandler(object sender, QuickIOTransferWorkerPickedJobEventArgs e); +/// +/// This event is raised when a new processing thread was created +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferWorkerCreatedHandler(object sender, QuickIOTransferWorkerCreatedEventArgs e); +/// +/// This event is raised when a processing thread started +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferWorkerStartedHandler(object sender, QuickIOTransferWorkerStartedEventArgs e); +/// +/// This event is raised when a processing thread was shutdown +/// +/// Transfer Service or Job +/// Provides further event information. +public delegate void QuickIOTransferWorkerShutdownHandler(object sender, QuickIOTransferWorkerShutdownEventArgs e); +#endregion diff --git a/src/QuickIO/Transfer/QuickIOTransferFileCopyErrorEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferFileCopyErrorEventArgs.cs new file mode 100644 index 0000000..05735d1 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferFileCopyErrorEventArgs.cs @@ -0,0 +1,25 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains further information when a file copy process fails +/// +public class QuickIOTransferFileCopyErrorEventArgs : QuickIOTransferJobWriteWithSourceEventArgs +{ + /// + /// Exception + /// + public Exception Exception { get; private set; } + + /// + /// Creates new instance of + /// + /// Affected job + /// Source file path + /// Target file path + /// Exception + public QuickIOTransferFileCopyErrorEventArgs(IQuickIOTransferJob job, string source, string target, Exception e) + : base(job, source, target) + { + Exception = e; + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferFileCopyFinishedEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferFileCopyFinishedEventArgs.cs new file mode 100644 index 0000000..6e58fcd --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferFileCopyFinishedEventArgs.cs @@ -0,0 +1,66 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information when a file copy operation has been finished successfully +/// +public class QuickIOTransferFileCopyFinishedEventArgs : QuickIOTransferJobWriteWithSourceEventArgs +{ + /// + /// Estimated Timestamp when transfer is finished + /// + public DateTime TransferFinished { get; private set; } + + + private TimeSpan? _duration; + + /// + /// Live transfer duration + /// + public TimeSpan Duration + { + get + { + return (TimeSpan)((TimeSpan?)(_duration ??= TransferFinished.Subtract(TransferStarted))); + } + } + + private double? _bytesPerSecond; + + /// + /// Live bytes per second + /// + public double BytesPerSecond + { + get + { + return (double)((double?)(_bytesPerSecond ??= (TotalBytes / Duration.TotalSeconds))); + } + } + + /// + /// Total bytes of file + /// + public ulong TotalBytes { get; private set; } + + + /// + /// Time transfer of file started + /// + public DateTime TransferStarted { get; private set; } + + /// + /// Creates new instance of + /// + /// Affected job + /// Source file path + /// Target file path + /// Total bytes to transfer + /// + public QuickIOTransferFileCopyFinishedEventArgs(IQuickIOTransferJob job, string sourcePath, string targetPath, long totalBytes, DateTime transferStarted) + : base(job, sourcePath, targetPath) + { + TotalBytes = (ulong)totalBytes; + TransferStarted = transferStarted; + TransferFinished = DateTime.Now; + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferFileCopyJob.cs b/src/QuickIO/Transfer/QuickIOTransferFileCopyJob.cs new file mode 100644 index 0000000..71b2fda --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferFileCopyJob.cs @@ -0,0 +1,392 @@ +using System.Diagnostics; +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// File Copy job implementation +/// +/// +/// File Copy job with observer +/// +/// +/// +/// +/// File copy job +/// +/// +/// +/// +/// Event definitions for this example +/// +/// +/// +/// +/// +public class QuickIOTransferFileCopyJob : QuickIOTransferJobWriteJob +{ + private volatile bool _copyTimestamps; + private DateTime? _transferStarted; + private readonly object _transferStartedLock = new( ); + + /// + /// Executes the Copy process + /// + protected override void Implementation() + { + ThrowIfCancellationRequested(); + + TransferStarted = DateTime.Now; + + QuickIOFileInfo sourceInfo = new( Source ); + QuickIOPathInfo targetFilePathInfo = new( Target ); + + if (targetFilePathInfo.Exists && !Overwrite) + { + throw new FileAlreadyExistsException(Target); + } + + ThrowIfCancellationRequested(); + + if (ParentExistanceCheck && targetFilePathInfo.Parent is not null) + { + OnDirectoryCreating(targetFilePathInfo.Parent.FullName); + + QuickIODirectory.Create(targetFilePathInfo.Parent, true); + + OnDirectoryCreated(targetFilePathInfo.Parent.FullName); + } + + ThrowIfCancellationRequested(); + + long totalBytes; + using (FileStream rs = sourceInfo.OpenRead()) + using (FileStream ws = QuickIOFile.Open(targetFilePathInfo, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) + { + totalBytes = rs.Length; + + OnCopyStarted(totalBytes); + + // set target stream length + ws.SetLength(totalBytes); + + int bytesRead; + ulong bytesTransfered = 0; + + // check buffer for small files; will be faster + byte[] bytes = new byte[ Math.Min( totalBytes, MaxBufferSize ) ]; + + // transfer chunks + while ((bytesRead = rs.Read(bytes, 0, bytes.Length)) > 0) + { + ThrowIfCancellationRequested(); + + // Write + ws.Write(bytes, 0, bytesRead); + + // Calculation + bytesTransfered = (bytesTransfered + (ulong)bytesRead); + + + OnCopyProgress(totalBytes, bytesTransfered); + } + } + + ThrowIfCancellationRequested(); + + // Copy Timestamps + if (CopyTimestamps) + { + QuickIOFile.SetAllFileTimes(targetFilePathInfo, sourceInfo.CreationTime, sourceInfo.LastAccessTime, sourceInfo.LastWriteTime); + } + + ThrowIfCancellationRequested(); + + // Copy Attributes + if (CopyAttributes) + { + QuickIOFile.SetAttributes(targetFilePathInfo, sourceInfo.Attributes); + } + + OnCopyFinished(totalBytes); + } + + /// + /// Fullname source + /// + public string Source { get; private set; } + + /// + /// Fullname target + /// + public string Target { get; private set; } + + + /// + /// Creates a new queue item + /// + /// Fullname source + /// Fullname target + /// Set max buffer size for copy transfer + /// true overwrites existing files + /// true to verify parent existance + /// Priority level of directory creation should be higher than file creation without parent check + public QuickIOTransferFileCopyJob(string source, string target, int maxBufferSize = 1024, bool overwrite = false, bool parentExistanceCheck = true, int prorityLevel = 0, CancellationToken cancellationToken = default) : + this(null, source, target, maxBufferSize, overwrite, parentExistanceCheck, prorityLevel, cancellationToken) + { } + + /// + /// Creates a new queue item + /// + /// Observer + /// Fullname source + /// Fullname target + /// Set max buffer size for copy transfer + /// true overwrites existing files + /// true to verify parent existance + /// Priority level of directory creation should be higher than file creation without parent check + public QuickIOTransferFileCopyJob(IQuickIOTransferObserver? observer, string source, string target, int maxBufferSize = 1024, bool overwrite = false, bool parentExistanceCheck = true, int prorityLevel = 0, CancellationToken cancellationToken = default) : + base(observer, prorityLevel, overwrite, cancellationToken) + { + Invariant.NotEmpty(source); + Invariant.NotEmpty(target); + + // Own + MaxBufferSize = Math.Max(1024, maxBufferSize); + Source = source; + Target = target; + ParentExistanceCheck = parentExistanceCheck; + } + + /// + /// Transfer started + /// + public DateTime? TransferStarted + { + get + { + lock (_transferStartedLock) + { + return _transferStarted; + } + } + internal set + { + lock (_transferStartedLock) + { + _transferStarted = value; + } + } + } + + /// + /// true to copy all datetime information such as CreationTime, LastAccessTime and LastWriteTime.
+ /// Default: false + ///
+ /// Will reduce the processing speed, because a single physical access is required for each setting. + public bool CopyTimestamps + { + get { return _copyTimestamps; } + set { _copyTimestamps = value; } + } + + /// + /// true to copy attribute information.
+ /// Default: false + ///
+ /// Will reduce the processing speed, because a single physical access is required for each setting. + public bool CopyAttributes + { + get { return _copyTimestamps; } + set { _copyTimestamps = value; } + } + + /// + /// This event is raised during a copy of a file. It provides current information such as progress, speed and estimated time. + /// + public event QuickIOTransferFileCopyProgressHandler? Progress; + + /// + /// This event is triggered at the beginning of the file copy operation. + /// + public event QuickIOTransferFileCopyStartedHandler? Started; + + /// + /// This event is raised if file copy operation fails + /// + public new event QuickIOTransferFileCopyErrorHandler? Error; + + /// + /// This event is raised at the end of the file copy operation. + /// + public event QuickIOTransferFileCopyFinishedHandler? Finished; + + /// + /// This event is raised before an upcoming directory creation operation is performed + /// + public event QuickIOTransferDirectoryCreatingHandler? DirectoryCreating; + + /// + /// This event is raised when a directory was created + /// + public event QuickIOTransferDirectoryCreatedHandler? DirectoryCreated; + + /// + /// Fire + /// + private void OnCopyProgress(long totalBytes, ulong bytesTransfered) + { + Debug.Assert(TransferStarted != null); + + QuickIOTransferFileCopyProgressEventArgs? args = null; + if (Progress != null) + { + args = new QuickIOTransferFileCopyProgressEventArgs(this, Source, Target, totalBytes, bytesTransfered, + (DateTime)TransferStarted); + Progress(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferFileCopyProgressEventArgs(this, Source, Target, totalBytes, bytesTransfered, + (DateTime)TransferStarted); + Observer.OnFileCopyProgress(args); + } + } + /// + /// Fires + /// + /// + protected override void OnError(Exception e) + { + // base throw not important + //base.OnError( e ); + + QuickIOTransferFileCopyErrorEventArgs? args = null; + if (Error != null) + { + args = new QuickIOTransferFileCopyErrorEventArgs(this, Source, Target, e); + Error(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferFileCopyErrorEventArgs(this, Source, Target, e); + Observer.OnFileCopyError(args); + } + } + + /// + /// Fire + /// + private void OnCopyStarted(long totalBytes) + { + QuickIOTransferFileCopyStartedEventArgs? args = null; + if (Started != null) + { + args = new QuickIOTransferFileCopyStartedEventArgs(this, Source, Target, totalBytes); + Started(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferFileCopyStartedEventArgs(this, Source, Target, totalBytes); + Observer.OnFileCopyStarted(args); + } + } + /// + /// Fire + /// + private void OnCopyFinished(long totalBytes) + { + Debug.Assert(TransferStarted != null); + + QuickIOTransferFileCopyFinishedEventArgs? args = null; + if (Finished != null) + { + args = new QuickIOTransferFileCopyFinishedEventArgs(this, Source, Target, totalBytes, (DateTime)TransferStarted); + Finished(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferFileCopyFinishedEventArgs(this, Source, Target, totalBytes, (DateTime)TransferStarted); + Observer.OnFileCopyFinished(args); + } + } + + /// + /// Fire + /// + private void OnDirectoryCreating(string directoryPath) + { + QuickIOTransferDirectoryCreatingEventArgs? args = null; + if (DirectoryCreating != null) + { + args = new QuickIOTransferDirectoryCreatingEventArgs(this, directoryPath); + DirectoryCreating(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferDirectoryCreatingEventArgs(this, directoryPath); + Observer.OnDirectoryCreating(args); + } + } + + /// + /// Fire + /// + private void OnDirectoryCreated(string directoryPath) + { + QuickIOTransferDirectoryCreatedEventArgs ? args = null; + if (DirectoryCreated != null) + { + args = new QuickIOTransferDirectoryCreatedEventArgs(this, directoryPath); + DirectoryCreated(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferDirectoryCreatedEventArgs(this, directoryPath); + Observer.OnDirectoryCreated(args); + } + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferFileCopyProgressEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferFileCopyProgressEventArgs.cs new file mode 100644 index 0000000..601f03a --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferFileCopyProgressEventArgs.cs @@ -0,0 +1,127 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Live progress information during file transfer. +/// +public class QuickIOTransferFileCopyProgressEventArgs : QuickIOTransferJobWriteWithSourceEventArgs +{ + /// + /// Total bytes of file transfered + /// + public ulong BytesTransfered { get; private set; } + + /// + /// Time the progress event was fired + /// + public DateTime ProgressTimestamp { get; private set; } + + private DateTime? _estimatedFinishTimestamp; + + /// + /// Estimated Timestamp when transfer is finished + /// + public DateTime EstimatedFinishTimestamp + { + get + { + return (DateTime)((DateTime?)(_estimatedFinishTimestamp ??= TransferStartedTimestamp.Add(EstimatedDuration))); + } + } + + private TimeSpan? _estimatedDuration; + /// + /// Estimated Duration + /// + public TimeSpan EstimatedDuration + { + get + { + return (TimeSpan)((TimeSpan?)(_estimatedDuration ??= TimeSpan.FromSeconds((TotalBytes / BytesPerSecond)))); + } + } + + private double? _percentage; + + /// + /// Total percentage + /// + public double Percentage + { + get + { + if (_percentage == null) + { + if (BytesTransfered == 0) + { + _percentage = 0; + } + else if (BytesTransfered == TotalBytes) + { + return 100; + } + else + { + _percentage = BytesTransfered * 1.0 / TotalBytes * 100.0; + } + } + + return (double)_percentage; + } + } + + private TimeSpan? _duration; + + /// + /// Live transfer duration + /// + public TimeSpan Duration + { + get + { + return (TimeSpan)((TimeSpan?)(_duration ??= ProgressTimestamp.Subtract(TransferStartedTimestamp))); + } + } + + + private double? _bytesPerSecond; + + /// + /// Live bytes per second + /// + public double BytesPerSecond + { + get + { + return (double)((double?)(_bytesPerSecond ??= (BytesTransfered / Duration.TotalSeconds))); + } + } + + /// + /// Total bytes of file + /// + public ulong TotalBytes { get; private set; } + + + /// + /// Time transfer of file started + /// + public DateTime TransferStartedTimestamp { get; private set; } + + /// + /// Creates new instance of + /// + /// Affected job + /// Source file path + /// Target file path + /// Total bytes to transfer + /// Total bytes transfered + /// + public QuickIOTransferFileCopyProgressEventArgs(IQuickIOTransferJob job, string sourcePath, string targetPath, long totalBytes, ulong bytesTransfered, DateTime transferStarted) + : base(job, sourcePath, targetPath) + { + TotalBytes = (ulong)totalBytes; + BytesTransfered = bytesTransfered; + TransferStartedTimestamp = transferStarted; + ProgressTimestamp = DateTime.Now; + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferFileCopyService.cs b/src/QuickIO/Transfer/QuickIOTransferFileCopyService.cs new file mode 100644 index 0000000..17f72d5 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferFileCopyService.cs @@ -0,0 +1,600 @@ +using SchwabenCode.QuickIO.Compatibility; + +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Copy directory with progress monitoring +/// +/// +/// Copy file +/// +/// +/// +/// +/// +/// +/// Copy collection of files +/// +/// +/// +public partial class QuickIOTransferFileCopyService : QuickIOTransferServiceBase +{ + /// + /// Directory to copy + /// + public List SourceFileInfos { get; private set; } + + /// + /// Target fullname + /// + public string TargetFullName { get; private set; } + + /// + /// true to overwrite existing content + /// + public bool Overwrite { get; set; } + + /// + /// Creates new instance of + /// + /// Observer for monitoring + /// File to copy + /// Target fullname + /// Copy Worker Counts. Use 1 on local systems. Use >2 with SMB shares + /// Count of retries before copy is broken + /// true to overwrite existing files + /// + /// Copy file + /// + /// + /// + /// + /// + public QuickIOTransferFileCopyService(IQuickIOTransferObserver observer, QuickIOFileInfo sourceFileInfo, string targetFullName, int threadCount = 1, int retryCount = 3, bool overwrite = false) + : this(observer, new List { sourceFileInfo }, targetFullName, threadCount, retryCount, overwrite) + { + + } + + + /// + /// Creates new instance of + /// + /// File to copy + /// Target fullname + /// Copy Worker Counts. Use 1 on local systems. Use >2 with SMB shares + /// Count of retries before copy is broken + /// true to overwrite existing files + /// + /// Copy file + /// + /// + /// + /// + /// + public QuickIOTransferFileCopyService(QuickIOFileInfo sourceFileInfo, string targetFullName, int threadCount = 1, int retryCount = 3, bool overwrite = false) + : this(null, new List { sourceFileInfo }, targetFullName, threadCount, retryCount, overwrite) + { + + } + + /// + /// Creates new instance of + /// + /// Files to copy + /// Target fullname + /// Copy Worker Counts. Use 1 on local systems. Use >2 with SMB shares + /// Count of retries before copy is broken + /// true to overwrite existing files + /// + /// Copy collection of files + /// + /// + /// + public QuickIOTransferFileCopyService(IEnumerable sourceFileInfos, string targetFullName, int threadCount = 1, int retryCount = 3, bool overwrite = false) + : this(null, sourceFileInfos, targetFullName, threadCount, retryCount, overwrite) + { + ; + } + + /// + /// Creates new instance of + /// + /// Observer for monitoring + /// Files to copy + /// Target fullname + /// Copy Worker Counts. Use 1 on local systems. Use >2 with SMB shares + /// Count of retries before copy is broken + /// true to overwrite existing files + /// + /// Copy collection of files + /// + /// + /// + public QuickIOTransferFileCopyService(IQuickIOTransferObserver? observer, IEnumerable sourceFileInfos, string targetFullName, int threadCount = 1, int retryCount = 3, bool overwrite = false) + : base(observer, threadCount, retryCount) + { + SourceFileInfos = new List(sourceFileInfos); + TargetFullName = targetFullName; + Overwrite = overwrite; + + // Register Events + RegisterInternalEventHandling(); + } + + private ulong _totalBytes; + private readonly object _totalBytesLock = new( ); + private ulong _totalBytesTransfered; + private readonly object _totalBytesTransferedLock = new( ); + + /// + /// Total bytes to transfer + /// + public ulong TotalBytes + { + get + { + lock (_totalBytesLock) + { + return _totalBytes; + } + } + private set + { + lock (_totalBytesLock) + { + _totalBytes = value; + } + } + } + + /// + /// Total bytes transfered + /// + public ulong TotalBytesTransfered + { + get + { + lock (_totalBytesTransferedLock) + { + return _totalBytesTransfered; + } + } + private set + { + lock (_totalBytesTransferedLock) + { + _totalBytesTransfered = value; + } + } + } + + /// + /// Null if not started + /// + public DateTime? TransferStarted { get; private set; } + + /// + /// Null if not finished + /// + public DateTime? TransferFinished { get; private set; } + + /// + /// Total duration. If transfer is not finished the current timestamp is used for the calculation + /// + public TimeSpan? Duration + { + get + { + if (TransferStarted == null) + { + return null; + } + return ((TransferFinished ?? DateTime.Now).Subtract((DateTime)TransferStarted)); + } + } + + /// + /// Bytes per second + /// + public double BytesPerSecond + { + get + { + ulong transfered = TotalBytesTransfered; + + TimeSpan? d = Duration; + if (d == null || transfered == 0) + { + return 0; + } + + return transfered * 1.0 / ((TimeSpan)d).TotalSeconds; + } + } + + /// + /// Bytes per second + /// + public double Percentage + { + get + { + ulong total = TotalBytes; + ulong transfered = TotalBytesTransfered; + + if (total == 0 || transfered == 0) + { + return 0; + } + if (total == transfered) + { + return 100; + } + + return (transfered * 1.0 / total * 100.0); + } + } + + /// + /// Starts the copy process. + /// First it determines all content information of source. Then the target directory structure will be created before transfer begins + /// + /// Service is already running. + /// Fired if you try to start a same service multiple times. + public void Start() + { + try + { + if (base.IsWorking) + { + throw new InvalidOperationException("Already running."); + } + + if (TransferFinished != null) + { + throw new ObjectDisposedException("Service already finished. Unable to start same service multiple times."); + } + + TransferStarted = DateTime.Now; + TransferFinished = null; + + string targetUnc = QuickIOPath.ToUncPath( TargetFullName ); + + List fileTransferQueueItems = []; + + foreach (QuickIOFileInfo file in SourceFileInfos) + { + + string target = targetUnc + QuickIOPath.DirectorySeparatorChar + file.Name; + fileTransferQueueItems.Add(new QuickIOTransferFileCopyJob(file.FullNameUnc, target, MaxBufferSize, Overwrite, true)); + TotalBytes += file.Bytes; + } + + InternalAddRange(fileTransferQueueItems); + + _ = base.StartWorking(); + + // No more will be added + CompleteAdding(); + + // Wait for finish + WaitForFinish(); + } + finally + { + TransferFinished = DateTime.Now; + } + } + + /// + /// Starts the copy process as task. + /// First it determines all content information of source. Then the target directory structure will be created before transfer begins + /// + public Task StartAsync() + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(Start); + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferFileCopyService_Events.cs b/src/QuickIO/Transfer/QuickIOTransferFileCopyService_Events.cs new file mode 100644 index 0000000..5bd98f2 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferFileCopyService_Events.cs @@ -0,0 +1,68 @@ +namespace SchwabenCode.QuickIO.Transfer; + +public partial class QuickIOTransferFileCopyService +{ + /// + /// Copy events from observer to current instance + /// + private void RegisterInternalEventHandling() + { + Observer.FileCopyError += (sender, e) => OnFileCopyError(e); + Observer.FileCopyFinished += (sender, e) => OnFileCopyFinished(e); + Observer.FileCopyProgress += (sender, e) => OnFileCopyProgress(e); + Observer.FileCopyStarted += (sender, e) => OnFileCopyStarted(e); + } + + /// + /// This event is raised if file copy operation fails + /// + public event QuickIOTransferFileCopyErrorHandler? FileCopyError; + + /// + /// This event is raised during a copy of a file. It provides current information such as progress, speed and estimated time. + /// + public event QuickIOTransferFileCopyProgressHandler? FileCopyProgress; + + /// + /// This event is triggered at the beginning of the file copy operation. + /// + public event QuickIOTransferFileCopyStartedHandler? FileCopyStarted; + + /// + /// This event is raised at the end of the file copy operation. + /// + public event QuickIOTransferFileCopyFinishedHandler? FileCopyFinished; + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCopyError(QuickIOTransferFileCopyErrorEventArgs args) + { + FileCopyError?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCopyProgress(QuickIOTransferFileCopyProgressEventArgs args) + { + FileCopyProgress?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCopyStarted(QuickIOTransferFileCopyStartedEventArgs args) + { + FileCopyStarted?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCopyFinished(QuickIOTransferFileCopyFinishedEventArgs args) + { + FileCopyFinished?.Invoke(this, args); + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferFileCopyStartedEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferFileCopyStartedEventArgs.cs new file mode 100644 index 0000000..0000684 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferFileCopyStartedEventArgs.cs @@ -0,0 +1,31 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information when a file copy process has been started +/// +public class QuickIOTransferFileCopyStartedEventArgs : QuickIOTransferJobWriteWithSourceEventArgs +{ + /// + /// Total bytes of file + /// + public ulong TotalBytes { get; private set; } + + /// + /// Time transfer of file started + /// + public DateTime TransferStarted { get; private set; } + + /// + /// Creates new instance of + /// + /// Affected job + /// Source file path + /// Affected job + /// Total bytes to transfer + public QuickIOTransferFileCopyStartedEventArgs(IQuickIOTransferJob job, string sourcePath, string targetPath, long totalBytes) + : base(job, sourcePath, targetPath) + { + TotalBytes = (ulong)totalBytes; + TransferStarted = DateTime.Now; + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferFileCreationErrorEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferFileCreationErrorEventArgs.cs new file mode 100644 index 0000000..15bb986 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferFileCreationErrorEventArgs.cs @@ -0,0 +1,24 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains further information when a file creation process fails +/// +public class QuickIOTransferFileCreationErrorEventArgs : QuickIOTransferJobWriteEventArgs +{ + /// + /// Exception + /// + public Exception Exception { get; private set; } + + /// + /// Creates new instance of + /// + /// Affected job + /// Target file path + /// Exception + public QuickIOTransferFileCreationErrorEventArgs(IQuickIOTransferJob job, string targetPath, Exception e) + : base(job, targetPath) + { + Exception = e; + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferFileCreationFinishedEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferFileCreationFinishedEventArgs.cs new file mode 100644 index 0000000..b82d613 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferFileCreationFinishedEventArgs.cs @@ -0,0 +1,65 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information when a file creation operation has been finished successfully +/// +public class QuickIOTransferFileCreationFinishedEventArgs : QuickIOTransferJobWriteEventArgs +{ + /// + /// Estimated Timestamp when transfer is finished + /// + public DateTime TransferFinished { get; private set; } + + + private TimeSpan? _duration; + + /// + /// Live transfer duration + /// + public TimeSpan Duration + { + get + { + return (TimeSpan)((TimeSpan?)(_duration ??= TransferFinished.Subtract(TransferStarted))); + } + } + + private double? _bytesPerSecond; + + /// + /// Live bytes per second + /// + public double BytesPerSecond + { + get + { + return (double)((double?)(_bytesPerSecond ??= (TotalBytes / Duration.TotalSeconds))); + } + } + + /// + /// Total bytes of file + /// + public ulong TotalBytes { get; private set; } + + + /// + /// Time transfer of file started + /// + public DateTime TransferStarted { get; private set; } + + /// + /// Creates new instance of + /// + /// Affected job + /// Target file path + /// Total bytes to transfer + /// + public QuickIOTransferFileCreationFinishedEventArgs(IQuickIOTransferJob job, string targetPath, long totalBytes, DateTime transferStarted) + : base(job, targetPath) + { + TotalBytes = (ulong)totalBytes; + TransferStarted = transferStarted; + TransferFinished = DateTime.Now; + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferFileCreationJob.cs b/src/QuickIO/Transfer/QuickIOTransferFileCreationJob.cs new file mode 100644 index 0000000..d3faf78 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferFileCreationJob.cs @@ -0,0 +1,381 @@ +using System.Diagnostics; +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// File Create job implementation +/// +/// +/// File Create job with observer +/// +/// +/// +/// +/// File create job +/// +/// +/// +/// +/// Event definitions for this example +/// +/// +/// +/// +/// +public class QuickIOTransferFileCreationJob : QuickIOTransferJobWriteJob +{ + private volatile int _maxJobRetryAttempts; + + #region Properties + + /// + /// Count of max retries per job + /// + public int MaxJobRetryAttempts + { + get { return _maxJobRetryAttempts; } + set { _maxJobRetryAttempts = value; } + } + + #endregion + + /// + /// Starts the creation process + /// + protected override void Implementation() + { + #region Cancel Check + ThrowIfCancellationRequested(); + #endregion + + TransferStarted = DateTime.Now; + + QuickIOPathInfo targetFullnameInfo = new( QuickIOPath.Combine( TargetDirectory, FileName ) ); + + if (targetFullnameInfo.Exists && !Overwrite) + { + CurrentRetryCount = MaxJobRetryAttempts; // no sense to requeue + throw new FileAlreadyExistsException(targetFullnameInfo.FullName); + } + + #region Cancel Check + ThrowIfCancellationRequested(); + #endregion + + + if (targetFullnameInfo.Parent?.Exists is true) + { + OnDirectoryCreating(targetFullnameInfo.Parent.FullName); + + QuickIODirectory.Create(targetFullnameInfo.Parent, true); + + OnDirectoryCreated(targetFullnameInfo.Parent.FullName); + } + + #region Cancel Check + ThrowIfCancellationRequested(); + #endregion + + + using MemoryStream rs = new(Contents); + using FileStream ws = QuickIOFile.Open(targetFullnameInfo, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); + long totalBytes = rs.Length; + + OnCreationStarted(totalBytes); + + // set target stream length + ws.SetLength(totalBytes); + + int bytesRead; + ulong bytesTransfered = 0; + + // check buffer for small files; will be faster + byte[] bytes = new byte[ Math.Min( totalBytes, MaxBufferSize ) ]; + + // transfer chunks + while ((bytesRead = rs.Read(bytes, 0, bytes.Length)) > 0) + { + #region Cancel Check + ThrowIfCancellationRequested(); + #endregion + + + // Write + ws.Write(bytes, 0, bytesRead); + + // Calculation + bytesTransfered = (bytesTransfered + (ulong)bytesRead); + + OnCreationProgress(totalBytes, bytesTransfered); + } + OnCreationFinished(totalBytes); + } + + + /// + /// Creates a new instance if + /// + /// Contents to write + /// Set max buffer size for copy transfer + /// true to overwrite existing elements + /// Target directory fullname + /// Target filename + /// true to verify parent existance + /// Priority level of directory creation should be higher than file creation without parent check + public QuickIOTransferFileCreationJob(string targetDirectory, string fileName, byte[] contents, int maxBufferSize = 1024, bool overwrite = false, bool parentExistanceCheck = true, int prorityLevel = 0) + : this(null, targetDirectory, fileName, contents, maxBufferSize, overwrite, parentExistanceCheck, prorityLevel) + { + } + + /// + /// Creates a new instance if + /// + /// Contents to write + /// true to overwrite existing elements + /// Set max buffer size for copy transfer + /// Observer + /// Target directory fullname + /// Target filename + /// true to verify parent existance + /// Priority level of directory creation should be higher than file creation without parent check + public QuickIOTransferFileCreationJob(IQuickIOTransferObserver? observer, string targetDirectory, string fileName, byte[] contents, int maxBufferSize = 1024, bool overwrite = false, bool parentExistanceCheck = true, int prorityLevel = 0) : + base(observer, prorityLevel) + { + Invariant.NotEmpty(targetDirectory); + Invariant.NotEmpty(fileName); + + // Parent + Overwrite = overwrite; + + //Own + MaxBufferSize = Math.Max(1024, maxBufferSize); + TargetDirectory = targetDirectory; + FileName = fileName; + Contents = contents; + ParentExistanceCheck = parentExistanceCheck; + + TargetFullName = QuickIOPath.Combine(TargetDirectory, FileName); + } + + /// + /// Target directory + /// + public string TargetDirectory { get; private set; } + + /// + /// Target directory + /// + public string TargetFullName { get; private set; } + + /// + /// Filename with extension + /// + public string FileName { get; private set; } + + /// + /// Contents to write + /// + public byte[] Contents { get; private set; } + + /// + /// Transfer started + /// + public DateTime? TransferStarted { get; internal set; } + + + #region Events + /// + /// This event is raised during a creation of a file. It provides current information such as progress, speed and estimated time. + /// + public event QuickIOTransferFileCreationProgressHandler? Progress; + + /// + /// This event is triggered at the beginning of the file creation operation. + /// + public event QuickIOTransferFileCreationStartedHandler? Started; + + /// + /// This event is raised at the end of the file creation operation. + /// + public event QuickIOTransferFileCreationFinishedHandler? Finished; + /// + /// This event is raised if file creation fails + /// + public new event QuickIOTransferFileCreationErrorHandler? Error; + + /// + /// This event is raised before an upcoming directory creation operation is performed + /// + public event QuickIOTransferDirectoryCreatingHandler? DirectoryCreating; + + /// + /// This event is raised when a directory was created + /// + public event QuickIOTransferDirectoryCreatedHandler? DirectoryCreated; + + /// + /// Fires + /// + private void OnCreationProgress(long totalBytes, ulong bytesTransfered) + { + Debug.Assert(TransferStarted != null); + + QuickIOTransferFileCreationProgressEventArgs? args = null; + if (Progress != null) + { + args = new QuickIOTransferFileCreationProgressEventArgs(this, TargetFullName, totalBytes, bytesTransfered, (DateTime)TransferStarted); + Progress(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferFileCreationProgressEventArgs(this, TargetFullName, totalBytes, bytesTransfered, (DateTime)TransferStarted); + Observer.OnFileCreationProgress(args); + } + } + /// + /// Fires + /// + private void OnCreationStarted(long totalBytes) + { + QuickIOTransferFileCreationStartedEventArgs? args = null; + if (Started != null) + { + args = new QuickIOTransferFileCreationStartedEventArgs(this, TargetFullName, totalBytes); + Started(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferFileCreationStartedEventArgs(this, TargetFullName, totalBytes); + Observer.OnFileCreationStarted(args); + } + } + /// + /// Fires + /// + private void OnCreationFinished(long totalBytes) + { + Debug.Assert(TransferStarted != null); + + QuickIOTransferFileCreationFinishedEventArgs? args = null; + if (Finished != null) + { + args = new QuickIOTransferFileCreationFinishedEventArgs(this, TargetFullName, totalBytes, (DateTime)TransferStarted); + Finished(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferFileCreationFinishedEventArgs(this, TargetFullName, totalBytes, (DateTime)TransferStarted); + Observer.OnFileCreationFinished(args); + } + } + + /// + /// Fires + /// + /// + protected override void OnError(Exception e) + { + // base throw not important + //base.OnError( e ); + + QuickIOTransferFileCreationErrorEventArgs? args = null; + if (Error != null) + { + args = new QuickIOTransferFileCreationErrorEventArgs(this, TargetFullName, e); + Error(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferFileCreationErrorEventArgs(this, TargetFullName, e); + Observer.OnFileCreationError(args); + } + } + + /// + /// Fire + /// + private void OnDirectoryCreating(string directoryPath) + { + QuickIOTransferDirectoryCreatingEventArgs? args = null; + if (DirectoryCreating != null) + { + args = new QuickIOTransferDirectoryCreatingEventArgs(this, directoryPath); + DirectoryCreating(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferDirectoryCreatingEventArgs(this, directoryPath); + Observer.OnDirectoryCreating(args); + } + } + + + /// + /// Fires + /// + private void OnDirectoryCreated(string directoryPath) + { + QuickIOTransferDirectoryCreatedEventArgs? args = null; + if (DirectoryCreated != null) + { + args = new QuickIOTransferDirectoryCreatedEventArgs(this, directoryPath); + DirectoryCreated(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferDirectoryCreatedEventArgs(this, directoryPath); + Observer.OnDirectoryCreated(args); + } + } + + #endregion +} diff --git a/src/QuickIO/Transfer/QuickIOTransferFileCreationProgressEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferFileCreationProgressEventArgs.cs new file mode 100644 index 0000000..1ee5441 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferFileCreationProgressEventArgs.cs @@ -0,0 +1,126 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Live progress information during file transfer. +/// +public class QuickIOTransferFileCreationProgressEventArgs : QuickIOTransferJobWriteEventArgs +{ + /// + /// Total bytes of file transfered + /// + public ulong BytesTransfered { get; private set; } + + /// + /// Time the progress event was fired + /// + public DateTime ProgressTimestamp { get; private set; } + + private DateTime? _estimatedFinishTimestamp; + + /// + /// Estimated Timestamp when transfer is finished + /// + public DateTime EstimatedFinishTimestamp + { + get + { + return (DateTime)((DateTime?)(_estimatedFinishTimestamp ??= TransferStartedTimestamp.Add(EstimatedDuration))); + } + } + + private TimeSpan? _estimatedDuration; + /// + /// Estimated Duration + /// + public TimeSpan EstimatedDuration + { + get + { + return (TimeSpan)((TimeSpan?)(_estimatedDuration ??= TimeSpan.FromSeconds((TotalBytes / BytesPerSecond)))); + } + } + + private double? _percentage; + + /// + /// Total percentage + /// + public double Percentage + { + get + { + if (_percentage == null) + { + if (BytesTransfered == 0) + { + _percentage = 0; + } + else if (BytesTransfered == TotalBytes) + { + return 100; + } + else + { + _percentage = BytesTransfered * 1.0 / TotalBytes * 100.0; + } + } + + return (double)_percentage; + } + } + + private TimeSpan? _duration; + + /// + /// Live transfer duration + /// + public TimeSpan Duration + { + get + { + return (TimeSpan)((TimeSpan?)(_duration ??= ProgressTimestamp.Subtract(TransferStartedTimestamp))); + } + } + + + private double? _bytesPerSecond; + + /// + /// Live bytes per second + /// + public double BytesPerSecond + { + get + { + return (double)((double?)(_bytesPerSecond ??= (BytesTransfered / Duration.TotalSeconds))); + } + } + + /// + /// Total bytes of file + /// + public ulong TotalBytes { get; private set; } + + + /// + /// Time transfer of file started + /// + public DateTime TransferStartedTimestamp { get; private set; } + + /// + /// Creates new instance of + /// + /// Affected job + /// Target file path + /// Total bytes to transfer + /// Total bytes transfered + /// + public QuickIOTransferFileCreationProgressEventArgs(IQuickIOTransferJob job, string targetPath, long totalBytes, ulong bytesTransfered, DateTime transferStarted) + : base(job, targetPath) + { + TotalBytes = (ulong)totalBytes; + BytesTransfered = bytesTransfered; + TransferStartedTimestamp = transferStarted; + ProgressTimestamp = DateTime.Now; + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferFileCreationStartedEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferFileCreationStartedEventArgs.cs new file mode 100644 index 0000000..2338b69 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferFileCreationStartedEventArgs.cs @@ -0,0 +1,30 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information when a file creation process has been started +/// +public class QuickIOTransferFileCreationStartedEventArgs : QuickIOTransferJobWriteEventArgs +{ + /// + /// Total bytes of file + /// + public ulong TotalBytes { get; private set; } + + /// + /// Time transfer of file started + /// + public DateTime TransferStarted { get; private set; } + + /// + /// Creates new instance of + /// + /// Affected job + /// Target file path + /// Total bytes to transfer + public QuickIOTransferFileCreationStartedEventArgs(IQuickIOTransferJob job, string targetPath, long totalBytes) + : base(job, targetPath) + { + TotalBytes = (ulong)totalBytes; + TransferStarted = DateTime.Now; + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJob.cs b/src/QuickIO/Transfer/QuickIOTransferJob.cs new file mode 100644 index 0000000..b67e0c3 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJob.cs @@ -0,0 +1,200 @@ +using SchwabenCode.QuickIO.Compatibility; + + +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// A job is a defined task is performed by the method +/// Here, you can define the content of the task itself. +/// +public abstract class QuickIOTransferJob : IQuickIOTransferJob +{ + + /// + /// Cancellation Token + /// + public CancellationToken Token { get; private set; } + + public void ThrowIfCancellationRequested() + { + Token.ThrowIfCancellationRequested(); + } + + /// + /// Central observer + /// + public IQuickIOTransferObserver? Observer { get; internal set; } + + /// + /// Creates a new instance of + /// + /// Observer for file monitoring by service + /// Default priority + /// Cancellation Token + /// Thread-safe + protected QuickIOTransferJob(IQuickIOTransferObserver? observer, int priorityLevel = 0, + CancellationToken cancellationToken = default) + { + Observer = observer; + CurrentRetryCount = priorityLevel; + + Token = cancellationToken; + } + + /// + /// Creates a new instance of + /// + /// Default priority + /// Cancellation Token + /// Thread-safe + protected QuickIOTransferJob(int priorityLevel = 0, CancellationToken cancellationToken = default) + : this(null, priorityLevel, cancellationToken) + { + } + + /// + /// Retry count before firing broken exception + /// + /// Thread-safe + public int CurrentRetryCount { get; set; } + + /// + /// Prority level. Higher priority = higher value. 0 = default + /// + /// Thread-safe + public int PriorityLevel { get; set; } + + /// + /// Implementation.
+ /// It is executed by default without a background thread. + /// The method can block. + ///
+ protected abstract void Implementation(); + + /// + /// Executes + /// + /// + /// Contains following content + /// + /// + /// + /// + /// + public void Run() + { + DateTime started = DateTime.Now; + OnRun(started); + + try + { + Implementation(); + } + catch (Exception e) + { + OnError(e); + throw; + } + + OnEnd(started, DateTime.Now); + } + + /// + /// Executes in Async context + /// + public Task RunAsync() + { + return NETCompatibility.AsyncExtensions.ExecuteAsync(Run); + } + + #region Events + /// + /// This event is raised when is called + /// + public event QuickIOTransferJobRunHandler? RunRaised; + + /// + /// This event is triggered if has an error + /// + public event QuickIOTransferJobErrorHandler? Error; + + /// + /// This event is raised at the end + /// + public event QuickIOTransferJobEndHandler? End; + + /// + /// Fires + /// + protected virtual void OnRun(DateTime started) + { + QuickIOTransferJobRunEventArgs? args = null; + if (RunRaised != null) + { + args = new QuickIOTransferJobRunEventArgs(this, started); + RunRaised(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferJobRunEventArgs(this, started); + Observer.OnJobRun(args); + } + } + + /// + /// Fires + /// + protected virtual void OnError(Exception e) + { + QuickIOTransferJobErrorEventArgs? args = null; + if (Error != null) + { + args = new QuickIOTransferJobErrorEventArgs(this, e); + Error(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferJobErrorEventArgs(this, e); + Observer.OnJobError(args); + } + } + + /// + /// Fires + /// + protected virtual void OnEnd(DateTime started, DateTime finished) + { + QuickIOTransferJobEndEventArgs? args = null; + if (End != null) + { + args = new QuickIOTransferJobEndEventArgs(this, started, finished); + End(this, args); + } + + if (Observer != null) + { + args ??= new QuickIOTransferJobEndEventArgs(this, started, finished); + Observer.OnJobEnd(args); + } + } + + #endregion +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobDequeuedEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferJobDequeuedEventArgs.cs new file mode 100644 index 0000000..1fe707e --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobDequeuedEventArgs.cs @@ -0,0 +1,21 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information of a dequeued job +/// +public class QuickIOTransferJobDequeuedEventArgs : EventArgs +{ + /// + /// Creates a new instance of + /// + /// Enqueued Job + public QuickIOTransferJobDequeuedEventArgs(IQuickIOTransferJob job) + { + Job = job; + } + + /// + /// Dequeued Job + /// + public IQuickIOTransferJob Job { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobEndEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferJobEndEventArgs.cs new file mode 100644 index 0000000..232e9e2 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobEndEventArgs.cs @@ -0,0 +1,30 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// provides information for job run +/// +public class QuickIOTransferJobEndEventArgs : QuickIOTransferJobEventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected job + /// Time of job start + /// Time of job end + public QuickIOTransferJobEndEventArgs(IQuickIOTransferJob job, DateTime jobStart, DateTime jobEnd) + : base(job) + { + StartTime = jobStart; + EndTime = jobEnd; + } + + /// + /// Time of job start + /// + public DateTime StartTime { get; private set; } + + /// + /// Time of job end + /// + public DateTime EndTime { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobEnqueuedEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferJobEnqueuedEventArgs.cs new file mode 100644 index 0000000..7ba3d2e --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobEnqueuedEventArgs.cs @@ -0,0 +1,21 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information of an enqueued job +/// +public class QuickIOTransferJobEnqueuedEventArgs : EventArgs +{ + /// + /// Creates a new instance of + /// + /// Enqueued Job + public QuickIOTransferJobEnqueuedEventArgs(IQuickIOTransferJob job) + { + Job = job; + } + + /// + /// Enqueued Job + /// + public IQuickIOTransferJob Job { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobErrorEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferJobErrorEventArgs.cs new file mode 100644 index 0000000..6df3a33 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobErrorEventArgs.cs @@ -0,0 +1,23 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// provides information for job error +/// +public class QuickIOTransferJobErrorEventArgs : QuickIOTransferJobEventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected job + /// Exception + public QuickIOTransferJobErrorEventArgs(IQuickIOTransferJob job, Exception e) + : base(job) + { + Exception = e; + } + + /// + /// Error + /// + public Exception Exception { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferJobEventArgs.cs new file mode 100644 index 0000000..16163ab --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobEventArgs.cs @@ -0,0 +1,22 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Abstract base class for job event arguments +/// +public abstract class QuickIOTransferJobEventArgs : EventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected job + protected QuickIOTransferJobEventArgs(IQuickIOTransferJob job) + { + Job = job; + } + + + /// + /// Target file path + /// + public IQuickIOTransferJob Job { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobPriorityComparer.cs b/src/QuickIO/Transfer/QuickIOTransferJobPriorityComparer.cs new file mode 100644 index 0000000..940997a --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobPriorityComparer.cs @@ -0,0 +1,37 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Job Priority Implementation +/// +internal class QuickIOTransferJobPriorityComparer : IComparer +{ + /// + /// Comparer Implementation - descending + /// + /// Left Job + /// Right Job + /// Higher Prio + public int Compare(IQuickIOTransferJob? leftJob, IQuickIOTransferJob? rightJob) + { + if (leftJob == null)// cancellation token + { + return 1; + } + if (rightJob == null)// cancellation token + { + return -1; + } + + if (leftJob.PriorityLevel < rightJob.PriorityLevel) + { + return 1; + } + + if (leftJob.PriorityLevel > rightJob.PriorityLevel) + { + return -1; + } + + return 0; + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobQueuedEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferJobQueuedEventArgs.cs new file mode 100644 index 0000000..1f44d09 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobQueuedEventArgs.cs @@ -0,0 +1,24 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information of an queued job +/// +public class QuickIOTransferJobQueuedEventArgs : QuickIOTransferJobWriteWithSourceEventArgs +{ + /// + /// Timestamp when the item has been added to the queue + /// + public DateTime AddedToQueue { get; private set; } + + /// + /// Creates a new instance of . Sets to DateTime.Now + /// + /// Affected job + /// Source file path + /// Target file path + public QuickIOTransferJobQueuedEventArgs(IQuickIOTransferJob job, string sourcePath, string targetPath) + : base(job, sourcePath, targetPath) + { + AddedToQueue = DateTime.Now; + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobReatryMaxReachedEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferJobReatryMaxReachedEventArgs.cs new file mode 100644 index 0000000..7f8bd73 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobReatryMaxReachedEventArgs.cs @@ -0,0 +1,28 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information if the max retry amount of a job has been reached +/// +public class QuickIOTransferJobReatryMaxReachedEventArgs : EventArgs +{ + /// + /// Creates a new instance of + /// + /// Enqueued Job + /// Last Exception occured + public QuickIOTransferJobReatryMaxReachedEventArgs(IQuickIOTransferJob job, Exception lastException) + { + Job = job; + LastException = lastException; + } + + /// + /// Requeued Job + /// + public IQuickIOTransferJob Job { get; private set; } + + /// + /// Raised exception caused the requeue + /// + public Exception LastException { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobRequeuedEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferJobRequeuedEventArgs.cs new file mode 100644 index 0000000..4524471 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobRequeuedEventArgs.cs @@ -0,0 +1,29 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information of a job that is re-queued. +/// A re-queue happens when a job execution failes and the service retries the operation +/// +public class QuickIOTransferJobRequeuedEventArgs : EventArgs +{ + /// + /// Creates a new instance of + /// + /// Enqueued Job + /// Exception of last error + public QuickIOTransferJobRequeuedEventArgs(IQuickIOTransferJob job, Exception e) + { + Job = job; + Exception = e; + } + + /// + /// Requeued Job + /// + public IQuickIOTransferJob Job { get; private set; } + + /// + /// Raised exception caused the requeue + /// + public Exception Exception { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobRunEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferJobRunEventArgs.cs new file mode 100644 index 0000000..83c0a58 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobRunEventArgs.cs @@ -0,0 +1,23 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// provides information for job run +/// +public class QuickIOTransferJobRunEventArgs : QuickIOTransferJobEventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected job + /// Time of job start + public QuickIOTransferJobRunEventArgs(IQuickIOTransferJob job, DateTime jobStart) + : base(job) + { + StartTime = jobStart; + } + + /// + /// Time of job start + /// + public DateTime StartTime { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobWriteEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferJobWriteEventArgs.cs new file mode 100644 index 0000000..3950f43 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobWriteEventArgs.cs @@ -0,0 +1,23 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Abstract base class for file transfer event arguments +/// +public abstract class QuickIOTransferJobWriteEventArgs : QuickIOTransferJobEventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected job + /// Target file path + protected QuickIOTransferJobWriteEventArgs(IQuickIOTransferJob job, string targetPath) + : base(job) + { + TargetPath = targetPath; + } + + /// + /// Target file path + /// + public string TargetPath { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobWriteJob.cs b/src/QuickIO/Transfer/QuickIOTransferJobWriteJob.cs new file mode 100644 index 0000000..3a9b816 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobWriteJob.cs @@ -0,0 +1,72 @@ +using System.ComponentModel; + +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Base class for transfer write jobs +/// +[Browsable(false)] +[EditorBrowsable(EditorBrowsableState.Never)] +public abstract class QuickIOTransferJobWriteJob : QuickIOTransferJob, IQuickIOTransferWriteJob +{ + private volatile int _maxBufferSize; + private volatile bool _parentExistanceCheck; + private volatile bool _overwrite; + + /// + /// Creates a new instance of + /// + /// Observer for file monitoring by service + /// Default priority + /// true to overwrite existing elements + /// Thread-safe + protected QuickIOTransferJobWriteJob(IQuickIOTransferObserver? observer, int priorityLevel = 0, bool overwrite = false, CancellationToken cancellationToken = default) : + base(observer, priorityLevel, cancellationToken) + { + _overwrite = overwrite; + } + + /// + /// Creates a new instance of + /// + /// Default priority + /// true to overwrite existing elements + /// Thread-safe + protected QuickIOTransferJobWriteJob(int priorityLevel = 0, bool overwrite = false +, CancellationToken cancellationToken = default +) + : this(null, priorityLevel, overwrite +, cancellationToken +) + { + + } + + /// + /// True to overwrite existing elements + /// + public bool Overwrite + { + get { return _overwrite; } + set { _overwrite = value; } + } + + /// + /// Max Buffer Size for Transfer + /// + public int MaxBufferSize + { + get { return _maxBufferSize; } + set { _maxBufferSize = value; } + } + + /// + /// True to check parent folder existance. False is much faster, but you have to be sure that the parent exists. + /// + public bool ParentExistanceCheck + { + get { return _parentExistanceCheck; } + protected set { _parentExistanceCheck = value; } + } + +} diff --git a/src/QuickIO/Transfer/QuickIOTransferJobWriteWithSourceEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferJobWriteWithSourceEventArgs.cs new file mode 100644 index 0000000..9967f47 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferJobWriteWithSourceEventArgs.cs @@ -0,0 +1,24 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Abstract class for other event argument implementaions +/// +public abstract class QuickIOTransferJobWriteWithSourceEventArgs : QuickIOTransferJobWriteEventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected job + /// Source path + /// target path + protected QuickIOTransferJobWriteWithSourceEventArgs(IQuickIOTransferJob job, string sourcePath, string targetPath) + : base(job, targetPath) + { + SourcePath = sourcePath; + } + + /// + /// Source file path + /// + public string SourcePath { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferObserver.cs b/src/QuickIO/Transfer/QuickIOTransferObserver.cs new file mode 100644 index 0000000..d4fcb52 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferObserver.cs @@ -0,0 +1,468 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// A QuickIO observer is a central contact point and allows the condition monitoring of QuickIO services and QuickIO jobs.
+/// It is possible to create an own observer by inherit from IQuickIOTransferObserver and QuickIOTransferObserver to monitor your own services and jobs at a central point and gather all information. +/// +/// If you define your own jobs you can create your own observer class that derives from , too. +/// +/// +/// Own observer example +/// +/// +/// /// My observer interface +/// ///
+/// public interface IMyExampleObserver : IQuickIOTransferObserver +/// { +/// /// +/// /// Description of MyEvent +/// /// +/// event MyExampleObserver.MyCustomEventHandler MyEvent; +/// +/// /// +/// /// Fire +/// /// +/// void OnMyEvent( ); +/// } +/// +/// /// +/// /// my observer implementation +/// /// +/// public class MyExampleObserver : QuickIOTransferObserver, IMyExampleObserver +/// { +/// /// +/// /// Delegate for +/// /// +/// public delegate void MyCustomEventHandler( object sender, EventArgs e ); +/// +/// /// +/// /// Description of MyEvent +/// /// +/// public event MyCustomEventHandler MyEvent; +/// +/// /// +/// /// Fire +/// /// +/// public virtual void OnMyEvent( ) +/// { +/// if ( MyEvent != null ) +/// { +/// MyEvent( this, EventArgs.Empty ); +/// } +/// } +/// +/// /// +/// /// For example we want to log each worker creation, but the keep the default behavior +/// /// +/// public override void OnWorkerCreated( QuickIOTransferWorkerCreatedEventArgs args ) +/// { +/// base.OnWorkerCreated( args ); +/// +/// QuickIOFile.AppendAllText( "Log_WorkerCreation.log", String.Format( "[{0}] NEW WORKER: {1} ", DateTime.Now, args.WorkerID ) ); +/// } +/// } +/// +/// /// +/// /// Example usage of own observer +/// /// +/// public class Program +/// { +/// /// +/// /// Program implementation +/// /// +/// public static void OwnObserverExample( ) +/// { +/// var myObserver = new MyExampleObserver( ); +/// +/// var service1 = new QuickIOTransferBackgroundService( myObserver, workerCount: 1 ); +/// var service2 = new QuickIOTransferBackgroundService( myObserver, workerCount: 4 ); +/// var directoryCopyService = new QuickIOTransferDirectoryCopyService( myObserver, new QuickIODirectoryInfo( @"C:\temp" ), @"C:\temp_testtarget" ); +/// +/// // service usage here +/// } +/// } +/// ]]> +/// +/// +public class QuickIOTransferObserver : IQuickIOTransferObserver +{ + /// + /// Creates a new instance of + /// + public QuickIOTransferObserver() + { + + } + + #region Directory Create + + /// + /// This event is raised if directory creation operation fails + /// + public event QuickIOTransferDirectoryCreationErrorHandler? DirectoryCreationError; + + /// + /// This event is raised before an upcoming directory creation operation is performed + /// + public event QuickIOTransferDirectoryCreatingHandler? DirectoryCreating; + + /// + /// This event is raised when a directory was created + /// + public event QuickIOTransferDirectoryCreatedHandler? DirectoryCreated; + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnDirectoryCreationError(QuickIOTransferDirectoryCreationErrorEventArgs args) + { + DirectoryCreationError?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnDirectoryCreating(QuickIOTransferDirectoryCreatingEventArgs args) + { + DirectoryCreating?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnDirectoryCreated(QuickIOTransferDirectoryCreatedEventArgs args) + { + DirectoryCreated?.Invoke(this, args); + } + #endregion + + #region File Creation + /// + /// This event is raised if file creation fails + /// + public event QuickIOTransferFileCreationErrorHandler? FileCreationError; + /// + /// This event is raised during a creation of a file. It provides current information such as progress, speed and estimated time. + /// + public event QuickIOTransferFileCreationProgressHandler? FileCreationProgress; + + /// + /// This event is triggered at the beginning of the file creation operation. + /// + public event QuickIOTransferFileCreationStartedHandler? FileCreationStarted; + + /// + /// This event is raised at the end of the file creation operation. + /// + public event QuickIOTransferFileCreationFinishedHandler? FileCreationFinished; + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCreationError(QuickIOTransferFileCreationErrorEventArgs args) + { + FileCreationError?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCreationProgress(QuickIOTransferFileCreationProgressEventArgs args) + { + FileCreationProgress?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCreationStarted(QuickIOTransferFileCreationStartedEventArgs args) + { + FileCreationStarted?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCreationFinished(QuickIOTransferFileCreationFinishedEventArgs args) + { + FileCreationFinished?.Invoke(this, args); + } + #endregion + + #region File Copy + + /// + /// This event is raised if file copy operation fails + /// + public event QuickIOTransferFileCopyErrorHandler? FileCopyError; + + /// + /// This event is raised during a copy of a file. It provides current information such as progress, speed and estimated time. + /// + public event QuickIOTransferFileCopyProgressHandler? FileCopyProgress; + + /// + /// This event is triggered at the beginning of the file copy operation. + /// + public event QuickIOTransferFileCopyStartedHandler? FileCopyStarted; + + /// + /// This event is raised at the end of the file copy operation. + /// + public event QuickIOTransferFileCopyFinishedHandler? FileCopyFinished; + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCopyError(QuickIOTransferFileCopyErrorEventArgs args) + { + FileCopyError?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCopyProgress(QuickIOTransferFileCopyProgressEventArgs args) + { + FileCopyProgress?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCopyStarted(QuickIOTransferFileCopyStartedEventArgs args) + { + FileCopyStarted?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnFileCopyFinished(QuickIOTransferFileCopyFinishedEventArgs args) + { + FileCopyFinished?.Invoke(this, args); + } + #endregion + + #region Service + /// + /// This event is raised if the service has been made known that no new elements will be added. + /// + public event QuickIOTransferCompletedAddingRequestedHandler? CompletedAddingRequested; + + + /// + /// This event is raised if the service has been made known that he should cancel the processing + /// + public event QuickIOTransferCancellationRequestedHandler? CancellationRequested; + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnCompletedAddingRequested(EventArgs args) + { + CompletedAddingRequested?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnCancellationRequested(EventArgs args) + { + CancellationRequested?.Invoke(this, args); + } + #endregion + + + #region Worker Events + + /// + /// This event is raised when a processing thread is waiting for new items + /// + public event QuickIOTransferWorkerIsWaitingHandler? WorkerIsWaiting; + + /// + /// This event is raised when a processing thread, which so far has been waiting for, was notified of a new item in the queue. + /// It may be that he gets no element from the queue, because another thread was faster. He would sleep lie down again, if no more items available. + /// + public event QuickIOTransferWorkerWokeUpHandler? WorkerWokeUp; + + /// + /// This event is raised when a processing thread has taken a new item from the queue + /// + public event QuickIOTransferWorkerPickedJobHandler? WorkerPickedJob; + + /// + /// This event is raised when a new processing thread was created + /// + public event QuickIOTransferWorkerCreatedHandler? WorkerCreated; + + /// + /// This event is raised when a processing thread started + /// + public event QuickIOTransferWorkerStartedHandler? WorkerStarted; + + /// + /// This event is raised when a processing thread was shutdown + /// + public event QuickIOTransferWorkerShutdownHandler? WorkerShutdown; + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnWorkerWokeUp(QuickIOTransferWorkerWokeUpEventArgs args) + { + WorkerWokeUp?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnWorkerIsWaiting(QuickIOTransferWorkerIsSleepingEventArgs args) + { + WorkerIsWaiting?.Invoke(this, args); + } + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnWorkerPickedJob(QuickIOTransferWorkerPickedJobEventArgs args) + { + WorkerPickedJob?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnWorkerCreated(QuickIOTransferWorkerCreatedEventArgs args) + { + WorkerCreated?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnWorkerStarted(QuickIOTransferWorkerStartedEventArgs args) + { + WorkerStarted?.Invoke(this, args); + } + /// + /// Fire + /// + /// Holds further event information + public virtual void OnWorkerShutdown(QuickIOTransferWorkerShutdownEventArgs args) + { + WorkerShutdown?.Invoke(this, args); + } + + #endregion + + #region Jobs + + /// + /// This event is raised when is called + /// + public event QuickIOTransferJobRunHandler? JobRun; + + /// + /// This event is triggered if has an error + /// + public event QuickIOTransferJobErrorHandler? JobError; + + /// + /// This event is raised at the end + /// + public event QuickIOTransferJobEndHandler? JobEnd; + + /// + /// This event is raised if the job of a queue has been added. + /// + public event QuickIOTransferJobEnqueuedHandler? JobEnqueued; + + /// + /// This event is raised if the job was taken from of a queue. + /// + public event QuickIOTransferJobDequeuedHandler? JobDequeued; + + /// + /// This event is raised if the job was re-added to a queue. + /// + public event QuickIOTransferJobRequeuedHandler? JobRequeued; + + /// + /// This event is raised if the max retry count is reached. + /// + public event QuickIOTransferJobRetryMaxReachedHandler? JobRetryMaxReached; + + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnJobRun(QuickIOTransferJobRunEventArgs args) + { + JobRun?.Invoke(this, args); + } + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnJobError(QuickIOTransferJobErrorEventArgs args) + { + JobError?.Invoke(this, args); + } + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnJobEnd(QuickIOTransferJobEndEventArgs args) + { + JobEnd?.Invoke(this, args); + } + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnJobEnqueued(QuickIOTransferJobEnqueuedEventArgs args) + { + JobEnqueued?.Invoke(this, args); + } + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnJobDequeued(QuickIOTransferJobDequeuedEventArgs args) + { + JobDequeued?.Invoke(this, args); + } + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnJobRequeued(QuickIOTransferJobRequeuedEventArgs args) + { + JobRequeued?.Invoke(this, args); + } + + /// + /// Fire + /// + /// Holds further event information + public virtual void OnJobRetryMaxReached(QuickIOTransferJobReatryMaxReachedEventArgs args) + { + JobRetryMaxReached?.Invoke(this, args); + } + #endregion +} diff --git a/src/QuickIO/Transfer/QuickIOTransferServiceBase.cs b/src/QuickIO/Transfer/QuickIOTransferServiceBase.cs new file mode 100644 index 0000000..62de7d5 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferServiceBase.cs @@ -0,0 +1,415 @@ +using System.ComponentModel; +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Base Class for transfer service implementations.
+///
+/// A QuickIO service is an instance for processing multiple jobs. QuickIO services offer multiple workers (one worker = one ), to enable parallel processing for jobs.
+/// By default the priority that a job has, is observed during the processing with . +///
+/// All methods and properties are thread-safe +[Browsable(false)] +[EditorBrowsable(EditorBrowsableState.Never)] +public partial class QuickIOTransferServiceBase +{ + private readonly object _workerShutdownLock = new( ); + private volatile int _maxWorkerCount; + private volatile int _workerCountRemoveRequested; + private readonly Dictionary _workerThreads; + private readonly object _workerCountRemoveRequestedLock = new( ); + + /// + /// Provides Events and Settings for transfer monitoring + /// + public IQuickIOTransferObserver Observer { get; private set; } + + + /// + /// Max count of active workers + /// + public int MaxWorkerCount + { + get + { + return _maxWorkerCount; + } + private set + { + _maxWorkerCount = value; + } + } + + #region Fields + private int _maxBufferSize = 32768; + private volatile int _maxJobRetryAttempts; + private readonly object _jobQueueLock = new( ); + private readonly object _workerThreadsLock = new( ); + #endregion + + /// + /// Size of Buffer + /// + public int MaxBufferSize + { + get + { + return _maxBufferSize; + } + private set + { + _maxBufferSize = Math.Max(1024, value); + } + } + /// + /// Max Job Retry Count + /// + public int MaxJobRetryAttempts + { + get + { + return _maxJobRetryAttempts; + } + private set + { + _maxJobRetryAttempts = Math.Max(1, value); + } + } + + /// + /// Count of active workers + /// + public int WorkerCount + { + get + { + lock (_workerThreadsLock) + { + return _workerThreads.Count; + } + } + } + + /// + /// True if service is running + /// + protected bool IsWorking + { + get { return WorkerCount != 0; } + } + + /// + /// Starts the service + /// + /// false if service is already started + protected bool StartWorking() + { + if (IsWorking) + { + return false; + } + + CreateWorkers(); + StartWorkers(); + + return true; + } + + #region Finalizing + + /// + /// true is cancel is requested + /// + public bool CancelRequested { get; private set; } + + /// + /// true if queue adding is completed. No more items will be added. + /// + public bool AddingCompleted { get; private set; } + + /// + /// Cancels the file provider and all transfers + /// + public void Cancel() + { + OnCancellationRequested(); + + CancelRequested = true; + } + + /// + /// Marks the queue as completed. No more items can be added. + /// + public void CompleteAdding() + { + OnCompletedAddingRequested(); + + AddingCompleted = true; + + lock (_workerThreadsLock) + { + foreach (KeyValuePair w in _workerThreads) + { + WakeUpSleepingWorkers(); + } + } + } + #endregion + + /// + /// Comparer for job sorting. By default it's . + /// FIFO if comparer is null. + /// + public IComparer PriorityComparer { get; set; } + + /// + /// Resorts the Queue + /// + private void InternalReSortLockedQueue() + { + if (PriorityComparer != null) + { + _jobQueue.Sort(PriorityComparer); + } + } + /// + /// Queue + /// + private readonly List _jobQueue = []; + + /// + /// Creates a new instance of + /// + /// Required server. Can be null to create default observer + /// Count of parallel workers to transfer the files + /// Max retry on transfer failure + protected QuickIOTransferServiceBase(IQuickIOTransferObserver? observer, int maxWorkerCount = 1, int maxFileRetry = 3) + { + MaxWorkerCount = maxWorkerCount; + _maxJobRetryAttempts = Math.Max(1, maxFileRetry); + _workerThreads = []; + + Observer = observer ?? new QuickIOTransferObserver(); + PriorityComparer = new QuickIOTransferJobPriorityComparer(); + } + + /// + /// Creates the amount of workers + /// + protected void CreateWorkers() + { + lock (_workerThreadsLock) + { + for (int i = 0; i < MaxWorkerCount; i++) + { + _ = InternalCreateNewWorker(); + } + } + } + + /// + /// Creates a new worker + /// + /// Created thread + private Thread InternalCreateNewWorker() + { + ParameterizedThreadStart tParams = new( StartConsuming ); + + Thread wt = new( tParams ); + _workerThreads.Add(wt.ManagedThreadId, wt); + OnWorkerCreated(wt.ManagedThreadId); + + return wt; + } + + /// + /// Creates the amount of workers + /// + protected void StartWorkers() + { + lock (_workerThreadsLock) + { + foreach (KeyValuePair w in _workerThreads) + { + Thread worker = w.Value; + InternalStartWorker(worker); + } + } + } + + /// + /// Starts the given worker by ID + /// + private void InternalStartWorker(Thread wt) + { + if (wt.IsAlive) + { + return; + } + + wt.Start(wt.ManagedThreadId); + OnWorkerStarted(wt.ManagedThreadId); + } + + /// + /// Adds a new worker to the service. Worker will be created and started instantly. + /// + /// Must be 1 or greater + /// It's not recommended to use more workers than the count of useable CPU cores. + protected void AddWorker(int count = 1) + { + Invariant.Greater(count, 0); + + lock (_workerThreadsLock) + { + for (int i = 0; i < count; i++) + { + Thread w = InternalCreateNewWorker( ); + InternalStartWorker(w); + } + } + } + + /// + /// Remove workers from the service. + /// + /// Must be 1 or greater + protected void RemoveWorker(int count = 1) + { + Invariant.Greater(count, 0); + + lock (_workerCountRemoveRequestedLock) + { + _workerCountRemoveRequested += count; + } + + WakeUpSleepingWorkers(); + + } + + /// + /// Wakes sleeping workers up + /// + private void WakeUpSleepingWorkers() + { + lock (_jobQueueLock) + { + Monitor.Pulse(_jobQueueLock); + } + } + + /// + /// waits for queue items + /// + private void InternalWaitForNewQueueItems() + { + _ = Monitor.Wait(_jobQueueLock); + } + + /// + /// Locks the queue and adds the element. + /// + /// Item to add + /// The service will inject his observer to the job. If the job already has an observer, it will be overwritten. + protected void InternalAdd(QuickIOTransferJob queueItem) + { + queueItem.Observer = Observer; + + lock (_jobQueueLock) + { + _jobQueue.Add(queueItem); + + InternalReSortLockedQueue(); // Sort by priority + + Monitor.Pulse(_jobQueueLock); // wake up sleeping workers + } + + OnJobEnqueued(queueItem); + } + + /// + /// Locks the queue and adds the collection to the queue. + /// + /// Collection of items to add + protected void InternalAddRange(IEnumerable queueItems) + { + lock (_jobQueueLock) + { + foreach (QuickIOTransferJob queueItem in queueItems) + { + queueItem.Observer = Observer; + + _jobQueue.Add(queueItem); + OnJobEnqueued(queueItem); + } + + InternalReSortLockedQueue(); // Sort by priority + + Monitor.Pulse(_jobQueueLock);// wake up sleeping workers + } + } + + /// + /// Clears the queue and returns all queued elements + /// + /// Collection of + protected IEnumerable Clear() + { + List queued; + lock (_jobQueue) + { + queued = new List(_jobQueue); + _jobQueue.Clear(); + } + + return queued; + } + + /// + /// Joins all threads and blocks until all threads and queue items are completed. + /// Queue has to be completed. + /// + protected void WaitForFinish() + { + if (!AddingCompleted) + { + throw new Exception("Queue is not completed."); + } + + lock (_workerThreadsLock) + { + if (_workerThreads.Count == 0) + { + return; + } + } + + lock (_workerShutdownLock) + { + _ = Monitor.Wait(_workerShutdownLock); + } + } + + /// + /// Removes a Thread from and raises + /// + /// Affcted Thread ID + private void RemoveThread(int threadId) + { + lock (_workerThreadsLock) + { + _ = _workerThreads.Remove(threadId); + + if (_workerThreads.Count == 0) + { + lock (_workerShutdownLock) + { + Monitor.Pulse(_workerShutdownLock); + } + } + } + OnWorkerShutdown(threadId); + } + +} diff --git a/src/QuickIO/Transfer/QuickIOTransferServiceBase_Events.cs b/src/QuickIO/Transfer/QuickIOTransferServiceBase_Events.cs new file mode 100644 index 0000000..cc27302 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferServiceBase_Events.cs @@ -0,0 +1,277 @@ +namespace SchwabenCode.QuickIO.Transfer; + +public partial class QuickIOTransferServiceBase +{ + #region Service Events + + /// + /// This event is raised if the service has been made known that no new elements will be added. + /// + public event QuickIOTransferCompletedAddingRequestedHandler? CompletedAddingRequested; + + + /// + /// This event is raised if the service has been made known that he should cancel the processing + /// + public event QuickIOTransferCancellationRequestedHandler? CancellationRequested; + + + /// + /// Fire + /// + private void OnCompletedAddingRequested() + { + EventArgs? args = null; + if (CompletedAddingRequested != null) + { + args = new EventArgs(); + CompletedAddingRequested(this, args); + } + + args ??= new EventArgs(); + Observer.OnCompletedAddingRequested(args); + } + /// + /// Fire + /// + private void OnCancellationRequested() + { + EventArgs? args = null; + if (CancellationRequested != null) + { + args = new EventArgs(); + CancellationRequested(this, args); + } + + args ??= new EventArgs(); + Observer.OnCancellationRequested(args); + } + #endregion + + #region Worker Events + + /// + /// This event is raised when a processing thread is waiting for new items + /// + public event QuickIOTransferWorkerIsWaitingHandler? WorkerIsWaiting; + + /// + /// This event is raised when a processing thread, which so far has been waiting for, was notified of a new item in the queue. + /// It may be that he gets no element from the queue, because another thread was faster. He would sleep lie down again, if no more items available. + /// + public event QuickIOTransferWorkerWokeUpHandler? WorkerWokeUp; + + /// + /// This event is raised when a processing thread has taken a new item from the queue + /// + public event QuickIOTransferWorkerPickedJobHandler? WorkerPickedJob; + + /// + /// This event is raised when a new processing thread was created + /// + public event QuickIOTransferWorkerCreatedHandler? WorkerCreated; + + /// + /// This event is raised when a processing thread started + /// + public event QuickIOTransferWorkerStartedHandler? WorkerStarted; + + /// + /// This event is raised when a processing thread was shutdown + /// + public event QuickIOTransferWorkerShutdownHandler? WorkerShutdown; + + /// + /// Fire + /// + /// affcted Worker Thread ID + private void OnWorkerWokeUp(int threadId) + { + QuickIOTransferWorkerWokeUpEventArgs? args = null; + if (WorkerWokeUp != null) + { + args = new QuickIOTransferWorkerWokeUpEventArgs(threadId); + WorkerWokeUp(this, args); + } + + args ??= new QuickIOTransferWorkerWokeUpEventArgs(threadId); + Observer.OnWorkerWokeUp(args); + } + /// + /// Fire + /// + /// affcted Worker Thread ID + private void OnWorkerIsWaiting(int threadId) + { + QuickIOTransferWorkerIsSleepingEventArgs? args = null; + if (WorkerIsWaiting != null) + { + args = new QuickIOTransferWorkerIsSleepingEventArgs(threadId); + WorkerIsWaiting(this, args); + } + + args ??= new QuickIOTransferWorkerIsSleepingEventArgs(threadId); + Observer.OnWorkerIsWaiting(args); + } + + /// + /// Fire + /// + /// affcted Worker Thread ID + /// picked job + private void OnWorkerPickedJob(int threadId, IQuickIOTransferJob job) + { + QuickIOTransferWorkerPickedJobEventArgs? args = null; + if (WorkerPickedJob != null) + { + args = new QuickIOTransferWorkerPickedJobEventArgs(threadId, job); + WorkerPickedJob(this, args); + } + + args ??= new QuickIOTransferWorkerPickedJobEventArgs(threadId, job); + Observer.OnWorkerPickedJob(args); + } + /// + /// Fire + /// + /// affcted Worker Thread ID + private void OnWorkerCreated(int threadId) + { + QuickIOTransferWorkerCreatedEventArgs? args = null; + if (WorkerCreated != null) + { + args = new QuickIOTransferWorkerCreatedEventArgs(threadId); + WorkerCreated(this, args); + } + + args ??= new QuickIOTransferWorkerCreatedEventArgs(threadId); + Observer.OnWorkerCreated(args); + } + /// + /// Fire + /// + /// affcted Worker Thread ID + private void OnWorkerStarted(int threadId) + { + QuickIOTransferWorkerStartedEventArgs? args = null; + if (WorkerStarted != null) + { + args = new QuickIOTransferWorkerStartedEventArgs(threadId); + WorkerStarted(this, args); + } + + args ??= new QuickIOTransferWorkerStartedEventArgs(threadId); + Observer.OnWorkerStarted(args); + } + /// + /// Fire + /// + /// affcted Worker Thread ID + private void OnWorkerShutdown(int threadId) + { + QuickIOTransferWorkerShutdownEventArgs? args = null; + if (WorkerShutdown != null) + { + args = new QuickIOTransferWorkerShutdownEventArgs(threadId); + WorkerShutdown(this, args); + } + + args ??= new QuickIOTransferWorkerShutdownEventArgs(threadId); + Observer.OnWorkerShutdown(args); + } + + #endregion + + #region Jobs + /// + /// This event is raised if the job of a queue has been added. + /// + public event QuickIOTransferJobEnqueuedHandler? JobEnqueued; + + /// + /// This event is raised if the job was taken from of a queue. + /// + public event QuickIOTransferJobDequeuedHandler? JobDequeued; + + /// + /// This event is raised if the job was re-added to a queue. + /// + public event QuickIOTransferJobRequeuedHandler? JobRequeued; + + /// + /// This event is raised if the max retry count is reached. + /// + public event QuickIOTransferJobRetryMaxReachedHandler? JobRetryMaxReached; + + /// + /// Fire + /// + /// Affected job + protected void OnJobEnqueued(IQuickIOTransferJob job) + { + QuickIOTransferJobEnqueuedEventArgs? args = null; + if (JobEnqueued != null) + { + args = new QuickIOTransferJobEnqueuedEventArgs(job); + JobEnqueued(this, args); + } + + args ??= new QuickIOTransferJobEnqueuedEventArgs(job); + Observer.OnJobEnqueued(args); + } + + /// + /// Fire + /// + /// Affected job + protected void OnJobDequeued(IQuickIOTransferJob job) + { + QuickIOTransferJobDequeuedEventArgs? args = null; + if (JobDequeued != null) + { + args = new QuickIOTransferJobDequeuedEventArgs(job); + JobDequeued(this, args); + } + + args ??= new QuickIOTransferJobDequeuedEventArgs(job); + Observer.OnJobDequeued(args); + } + + /// + /// Fire for this service and specified observer + /// + /// Affected job + /// Caused exception + protected void OnJobRequeued(IQuickIOTransferJob job, Exception e) + { + QuickIOTransferJobRequeuedEventArgs? args = null; + if (JobRequeued != null) + { + args = new QuickIOTransferJobRequeuedEventArgs(job, e); + JobRequeued(this, args); + } + + args ??= new QuickIOTransferJobRequeuedEventArgs(job, e); + Observer.OnJobRequeued(args); + } + + /// + /// Fire + /// + /// Affected job + /// Last exception + protected void OnJobRetryMaxReached(IQuickIOTransferJob job, Exception lastException) + { + QuickIOTransferJobReatryMaxReachedEventArgs? args = null; + if (JobRetryMaxReached != null) + { + args = new QuickIOTransferJobReatryMaxReachedEventArgs(job, lastException); + JobRetryMaxReached(this, args); + } + + args ??= new QuickIOTransferJobReatryMaxReachedEventArgs(job, lastException); + Observer.OnJobRetryMaxReached(args); + } + #endregion + +} diff --git a/src/QuickIO/Transfer/QuickIOTransferServiceBase_Executions.cs b/src/QuickIO/Transfer/QuickIOTransferServiceBase_Executions.cs new file mode 100644 index 0000000..b74373d --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferServiceBase_Executions.cs @@ -0,0 +1,112 @@ +namespace SchwabenCode.QuickIO.Transfer; + +public partial class QuickIOTransferServiceBase +{ + /// + /// Element consuming. Breaks if element is null. + /// + private void StartConsuming(object? threadId) + { + int tID = ( int ) threadId!; + + while (true) + { + // while one thread is waiting for a new item + // all other thrads are waiting at this lock point + lock (_jobQueueLock) + { + // Check for canceleation + if (CancelRequested) + { + RemoveThread(tID); + return; + } + + // Remove? + lock (_workerCountRemoveRequestedLock) + { + if (_workerCountRemoveRequested > 0) + { + _workerCountRemoveRequested--; + RemoveThread(tID); + return; + } + } + + // block while no new entry is in queue + if (_jobQueue.Count == 0) + { + if (AddingCompleted) + { + RemoveThread(tID); + return; + } + + OnWorkerIsWaiting(tID); + + // one thread is waiting here for new items! + InternalWaitForNewQueueItems(); + + OnWorkerWokeUp(tID); + } + + // we have to check the count here again, cause the wakeup + // can be caused by remove thread! + if (_jobQueue.Count > 0) + { + // Get first item in queue + IQuickIOTransferJob job = _jobQueue[ 0 ]; + _jobQueue.RemoveAt(0); + + OnWorkerPickedJob(tID, job); + JobExecuteSwitch(job); + } + } + } + } + + /// + /// Consuming - transfer file + /// + /// Queue Item + private void JobExecuteSwitch(IQuickIOTransferJob job) + { + OnJobDequeued(job); + + job.CurrentRetryCount++; + + try + { + job.Run(); + } + catch (Exception e) + { + // Retry count reached?! + if (job.CurrentRetryCount >= _maxJobRetryAttempts) + { + OnJobRetryMaxReached(job, e); + return; + } + + // Increase retry count and re-add to the queue + job.CurrentRetryCount++; + lock (_jobQueueLock) + { + // on empty queue just add + if (_jobQueue.Count == 0) + { + _jobQueue.Add(job); + } + else + { + _jobQueue.Insert(_jobQueue.Count - 1, job); + } + + InternalReSortLockedQueue(); // resort queue + } + + OnJobRequeued(job, e); + } + + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferSetTimestampsJob.cs b/src/QuickIO/Transfer/QuickIOTransferSetTimestampsJob.cs new file mode 100644 index 0000000..6e30aff --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferSetTimestampsJob.cs @@ -0,0 +1,73 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Job to set timestamps +/// +internal class QuickIOTransferSetTimestampsJob : QuickIOTransferJob +{ + /// + /// Implementation of this job + /// + protected override void Implementation() + { + throw new NotImplementedException(); + } + + /// + /// Targetpath + /// + public string TargetPath { get; private set; } + + #region Time Properties + #region UNC Times + /// + /// Gets the creation time (UTC) + /// + public DateTime CreationTimeUtc { get; private set; } + + /// + /// Gets the time (UTC) of last access. + /// + public DateTime LastAccessTimeUtc { get; private set; } + + /// + /// Gets the time (UTC) was last written to + /// + public DateTime LastWriteTimeUtc { get; private set; } + #endregion + + #region LocalTime + /// + /// Gets the creation time + /// + public DateTime CreationTime { get { return CreationTimeUtc.ToLocalTime(); } } + + /// + /// Gets the time that the file was last accessed + /// + public DateTime LastAccessTime { get { return LastAccessTimeUtc.ToLocalTime(); } } + + /// + /// Gets the time the file was last written to. + /// + public DateTime LastWriteTime { get { return LastWriteTimeUtc.ToLocalTime(); } } + #endregion + #endregion + + /// + /// Job for creating directory paths + /// + /// Affected fullname to set attributes + /// The time the file was last written to. + /// Priority level of directory creation should be higher than file creation without parent check + /// The creation time + /// The time that the file was last accessed + public QuickIOTransferSetTimestampsJob(string targetPath, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, int prorityLevel = -1) + : base(prorityLevel) + { + TargetPath = targetPath; + CreationTimeUtc = creationTime.ToUniversalTime(); + LastAccessTimeUtc = lastAccessTime.ToUniversalTime(); + LastWriteTimeUtc = lastWriteTime.ToUniversalTime(); + } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferWorkerCreatedEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferWorkerCreatedEventArgs.cs new file mode 100644 index 0000000..330c52d --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferWorkerCreatedEventArgs.cs @@ -0,0 +1,21 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information when a new worker has been created +/// +public class QuickIOTransferWorkerCreatedEventArgs : EventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected Worker ID + public QuickIOTransferWorkerCreatedEventArgs(int workerID) + { + WorkerID = workerID; + } + + /// + /// Affected Worker ID + /// + public int WorkerID { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferWorkerIsSleepingEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferWorkerIsSleepingEventArgs.cs new file mode 100644 index 0000000..91e8f5e --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferWorkerIsSleepingEventArgs.cs @@ -0,0 +1,21 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information if a workers wait for a new element in queue +/// +public class QuickIOTransferWorkerIsSleepingEventArgs : EventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected Worker ID + public QuickIOTransferWorkerIsSleepingEventArgs(int workerID) + { + WorkerID = workerID; + } + + /// + /// Affected Worker ID + /// + public int WorkerID { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferWorkerPickedJobEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferWorkerPickedJobEventArgs.cs new file mode 100644 index 0000000..869a810 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferWorkerPickedJobEventArgs.cs @@ -0,0 +1,29 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information when a worker picked up a new job from the queue +/// +public class QuickIOTransferWorkerPickedJobEventArgs : EventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected Worker ID + /// Picked job + public QuickIOTransferWorkerPickedJobEventArgs(int workerID, IQuickIOTransferJob job) + { + WorkerID = workerID; + Job = job; + } + + /// + /// Affected Worker ID + /// + public int WorkerID { get; private set; } + + + /// + /// Picked Job + /// + public IQuickIOTransferJob Job { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferWorkerShutdownEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferWorkerShutdownEventArgs.cs new file mode 100644 index 0000000..1d0bea7 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferWorkerShutdownEventArgs.cs @@ -0,0 +1,21 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information when a worker has stopped successfully +/// +public class QuickIOTransferWorkerShutdownEventArgs : EventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected Worker ID + public QuickIOTransferWorkerShutdownEventArgs(int workerID) + { + WorkerID = workerID; + } + + /// + /// Affected Worker ID + /// + public int WorkerID { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferWorkerStartedEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferWorkerStartedEventArgs.cs new file mode 100644 index 0000000..df74859 --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferWorkerStartedEventArgs.cs @@ -0,0 +1,21 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information when a worker started +/// +public class QuickIOTransferWorkerStartedEventArgs : EventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected Worker ID + public QuickIOTransferWorkerStartedEventArgs(int workerID) + { + WorkerID = workerID; + } + + /// + /// Affected Worker ID + /// + public int WorkerID { get; private set; } +} diff --git a/src/QuickIO/Transfer/QuickIOTransferWorkerWokeUpEventArgs.cs b/src/QuickIO/Transfer/QuickIOTransferWorkerWokeUpEventArgs.cs new file mode 100644 index 0000000..ca8317c --- /dev/null +++ b/src/QuickIO/Transfer/QuickIOTransferWorkerWokeUpEventArgs.cs @@ -0,0 +1,22 @@ +namespace SchwabenCode.QuickIO.Transfer; + +/// +/// Contains information when when a worker, which so far has been waiting for an item, was notified of a new item in the queue. +/// It may be that he gets no element from the queue, because another thread was faster. He would sleep lie down again, if no more items available. +/// +public class QuickIOTransferWorkerWokeUpEventArgs : EventArgs +{ + /// + /// Creates a new instance of + /// + /// Affected Worker ID + public QuickIOTransferWorkerWokeUpEventArgs(int workerID) + { + WorkerID = workerID; + } + + /// + /// Affected Worker ID + /// + public int WorkerID { get; private set; } +} diff --git a/src/QuickIO/UnmatchedFileSystemEntryTypeException.cs b/src/QuickIO/UnmatchedFileSystemEntryTypeException.cs new file mode 100644 index 0000000..e058400 --- /dev/null +++ b/src/QuickIO/UnmatchedFileSystemEntryTypeException.cs @@ -0,0 +1,34 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Exception if path returns another type as excepted +/// +[Serializable] +public sealed class UnmatchedFileSystemEntryTypeException : Exception +{ + /// + /// Estimated Type + /// + public QuickIOFileSystemEntryType Estimated { get; private set; } + + /// + /// Type found + /// + public QuickIOFileSystemEntryType Found { get; private set; } + + /// + /// Affected full path + /// + public string FullName { get; private set; } + + /// + /// Exception if path returns another type as excepted + /// + public UnmatchedFileSystemEntryTypeException(QuickIOFileSystemEntryType estimated, QuickIOFileSystemEntryType found, string path) + : base("FileSystemEntryType not matched!") + { + Estimated = estimated; + Found = found; + FullName = path; + } +} diff --git a/src/QuickIO/UnsupportedDriveTypeException.cs b/src/QuickIO/UnsupportedDriveTypeException.cs new file mode 100644 index 0000000..10818d0 --- /dev/null +++ b/src/QuickIO/UnsupportedDriveTypeException.cs @@ -0,0 +1,16 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Represents an exception for unsuuported drive types +/// +public class UnsupportedDriveTypeException : QuickIOBaseException +{ + /// + /// Creates an instance of + /// + /// Unsupported drive + public UnsupportedDriveTypeException(string path) + : base("Unsupported Drive Type: only logical drives are supported; do not use mapped network drives.", path) + { + } +} diff --git a/src/QuickIO/UnsupportedShareTypeException.cs b/src/QuickIO/UnsupportedShareTypeException.cs new file mode 100644 index 0000000..835fd6e --- /dev/null +++ b/src/QuickIO/UnsupportedShareTypeException.cs @@ -0,0 +1,17 @@ +namespace SchwabenCode.QuickIO; + +/// +/// Represents an exception for unsuuported drive types +/// +public class UnsupportedShareTypeException : QuickIOBaseException +{ + /// + /// Creates an instance of + /// + /// Unsupported drive + /// Error + public UnsupportedShareTypeException(string path, string message) + : base(message, path) + { + } +} diff --git a/src/QuickIO/Win32API/QuickIOShareDetailedInfo.cs b/src/QuickIO/Win32API/QuickIOShareDetailedInfo.cs new file mode 100644 index 0000000..0683f35 --- /dev/null +++ b/src/QuickIO/Win32API/QuickIOShareDetailedInfo.cs @@ -0,0 +1,64 @@ +namespace SchwabenCode.QuickIO.Win32API; + +/// +/// Container of detailed share information +/// +public class QuickIOShareDetailedInfo +{ + /// + /// Transfers the struct information to the class + /// + /// share information + internal QuickIOShareDetailedInfo(Win32ApiShareInfoAdmin shareInfo) + { + Name = shareInfo.ShareName; + Type = shareInfo.ShareType; + Remark = shareInfo.Remark; + + Permissions = shareInfo.Permissions; + MaxUsers = shareInfo.MaxUsers; + CurrentUsers = shareInfo.CurrentUsers; + Path = shareInfo.Path; + Password = shareInfo.Password; + } + + /// + /// Name of Share + /// + public string Name { get; private set; } + + /// + /// Share Type + /// + public QuickIOShareType Type { get; private set; } + + /// + /// Remark / Comment + /// + public string Remark { get; private set; } + + /// + /// Permissions. Is null, if admin privileges are not granted. + /// + public int? Permissions { get; private set; } + + /// + /// MaxUsers of the parallel connected users. Is null, if admin privileges are not granted. + /// + public int? MaxUsers { get; private set; } + + /// + /// CurrentUsers connected to the share. Is null, if admin privileges are not granted. + /// + public int? CurrentUsers { get; private set; } + + /// + /// Permissions. Is null, if admin privileges are not granted. + /// + public string Path { get; private set; } + + /// + /// Password. Is null, if admin privileges are not granted. + /// + public string Password { get; private set; } +} diff --git a/src/QuickIO/Win32API/Win32ApiShareInfoAdmin.cs b/src/QuickIO/Win32API/Win32ApiShareInfoAdmin.cs new file mode 100644 index 0000000..7113e9d --- /dev/null +++ b/src/QuickIO/Win32API/Win32ApiShareInfoAdmin.cs @@ -0,0 +1,25 @@ + +using System.Runtime.InteropServices; + +namespace SchwabenCode.QuickIO.Win32API; + +/// +/// Gets the complete share information. Requires admin priviles. +/// +/// See http://msdn.microsoft.com/en-us/library/windows/desktop/bb525408(v=vs.85).aspx +[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] +internal struct Win32ApiShareInfoAdmin +{ + [MarshalAs( UnmanagedType.LPWStr )] + public string ShareName; + public QuickIOShareType ShareType; + [MarshalAs( UnmanagedType.LPWStr )] + public string Remark; + public int Permissions; + public int MaxUsers; + public int CurrentUsers; + [MarshalAs( UnmanagedType.LPWStr )] + public string Path; + [MarshalAs( UnmanagedType.LPWStr )] + public string Password; +} diff --git a/src/QuickIO/Win32API/Win32ApiShareInfoNormal.cs b/src/QuickIO/Win32API/Win32ApiShareInfoNormal.cs new file mode 100644 index 0000000..a4caad7 --- /dev/null +++ b/src/QuickIO/Win32API/Win32ApiShareInfoNormal.cs @@ -0,0 +1,18 @@ + +using System.Runtime.InteropServices; + +namespace SchwabenCode.QuickIO.Win32API; + +/// +/// Use this Info bag if call with admin privilegs fails (fallback) +/// +/// See http://msdn.microsoft.com/en-us/library/windows/desktop/bb525407(v=vs.85).aspx +[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] +internal struct Win32ApiShareInfoNormal +{ + [MarshalAs( UnmanagedType.LPWStr )] + public string ShareName; + public QuickIOShareType ShareType; + [MarshalAs( UnmanagedType.LPWStr )] + public string Remark; +} diff --git a/src/QuickIO/Win32API/Win32ErrorCodes.cs b/src/QuickIO/Win32API/Win32ErrorCodes.cs new file mode 100644 index 0000000..4603adb --- /dev/null +++ b/src/QuickIO/Win32API/Win32ErrorCodes.cs @@ -0,0 +1,458 @@ +namespace SchwabenCode.QuickIO.Win32API; + +/// +/// Win32 Error Code Collection +/// +internal class Win32ErrorCodes +{ + public const int ERROR_ACCESS_DENIED = 5; + public const int ERROR_ADAP_HDW_ERR = 57; + public const int ERROR_ALREADY_ASSIGNED = 85; + public const int ERROR_ALREADY_EXISTS = 183; + public const int ERROR_ARENA_TRASHED = 7; + public const int ERROR_ATOMIC_LOCKS_NOT_SUPPORTED = 174; + public const int ERROR_AUTODATASEG_EXCEEDS_64k = 199; + public const int ERROR_BAD_ARGUMENTS = 160; + public const int ERROR_BAD_COMMAND = 22; + public const int ERROR_BAD_DEV_TYPE = 66; + public const int ERROR_BAD_DRIVER_LEVEL = 119; + public const int ERROR_BAD_ENVIRONMENT = 10; + public const int ERROR_BAD_EXE_FORMAT = 193; + public const int ERROR_BAD_FILE_TYPE = 222; + public const int ERROR_BAD_FORMAT = 11; + public const int ERROR_BAD_LENGTH = 24; + public const int ERROR_BAD_NET_NAME = 67; + public const int ERROR_BAD_NET_RESP = 58; + public const int ERROR_BAD_NETPATH = 53; + public const int ERROR_BAD_PATHNAME = 161; + public const int ERROR_BAD_PIPE = 230; + public const int ERROR_BAD_REM_ADAP = 60; + public const int ERROR_BAD_THREADID_ADDR = 159; + public const int ERROR_BAD_UNIT = 20; + public const int ERROR_BROKEN_PIPE = 109; + public const int ERROR_BUFFER_OVERFLOW = 111; + public const int ERROR_BUSY_DRIVE = 142; + public const int ERROR_BUSY = 170; + public const int ERROR_CALL_NOT_IMPLEMENTED = 120; + public const int ERROR_CANCEL_VIOLATION = 173; + public const int ERROR_CANNOT_COPY = 266; + public const int ERROR_CANNOT_MAKE = 82; + public const int ERROR_CHECKOUT_REQUIRED = 221; + public const int ERROR_CHILD_NOT_COMPLETE = 129; + public const int ERROR_CRC = 23; + public const int ERROR_CURRENT_DIRECTORY = 16; + public const int ERROR_DELETE_PENDING = 303; + public const int ERROR_DEV_NOT_EXIST = 55; + public const int ERROR_DIR_NOT_EMPTY = 145; + public const int ERROR_DIR_NOT_ROOT = 144; + public const int ERROR_DIRECT_ACCESS_HANDLE = 130; + public const int ERROR_DIRECTORY = 267; + public const int ERROR_DISCARDED = 157; + public const int ERROR_DISK_CHANGE = 107; + public const int ERROR_DISK_FULL = 112; + public const int ERROR_DISK_TOO_FRAGMENTED = 302; + public const int ERROR_DRIVE_LOCKED = 108; + public const int ERROR_DUP_NAME = 52; + public const int ERROR_DYNLINK_FROM_INVALID_RING = 196; + public const int ERROR_EA_FILE_CORRUPT = 276; + public const int ERROR_EA_LIST_INCONSISTENT = 255; + public const int ERROR_EA_TABLE_FULL = 277; + public const int ERROR_EAS_DIDNT_FIT = 275; + public const int ERROR_EAS_NOT_SUPPORTED = 282; + public const int ERROR_ENVVAR_NOT_FOUND = 203; + public const int ERROR_EXCL_SEM_ALREADY_OWNED = 101; + public const int ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY = 217; + public const int ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY = 218; + public const int ERROR_EXE_MACHINE_TYPE_MISMATCH = 216; + public const int ERROR_EXE_MARKED_INVALID = 192; + public const int ERROR_FAIL_I24 = 83; + public const int ERROR_FAIL_NOACTION_REBOOT = 350; + public const int ERROR_FAIL_RESTART = 352; + public const int ERROR_FAIL_SHUTDOWN = 351; + public const int ERROR_FILE_CHECKED_OUT = 220; + public const int ERROR_FILE_EXISTS = 80; + public const int ERROR_FILE_NOT_FOUND = 2; + public const int ERROR_FILE_TOO_LARGE = 223; + public const int ERROR_FILENAME_EXCED_RANGE = 206; + public const int ERROR_FORMS_AUTH_REQUIRED = 224; + public const int ERROR_GEN_FAILURE = 31; + public const int ERROR_HANDLE_DISK_FULL = 39; + public const int ERROR_HANDLE_EOF = 38; + public const int ERROR_IMAGE_SUBSYSTEM_NOT_PRESENT = 308; + public const int ERROR_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING = 304; + public const int ERROR_INFLOOP_IN_RELOC_CHAIN = 202; + public const int ERROR_INSUFFICIENT_BUFFER = 122; + public const int ERROR_INVALID_ACCESS = 12; + public const int ERROR_INVALID_ADDRESS = 487; + public const int ERROR_INVALID_AT_INTERRUPT_TIME = 104; + public const int ERROR_INVALID_BLOCK = 9; + public const int ERROR_INVALID_CATEGORY = 117; + public const int ERROR_INVALID_DATA = 13; + public const int ERROR_INVALID_DRIVE = 15; + public const int ERROR_INVALID_EA_HANDLE = 278; + public const int ERROR_INVALID_EA_NAME = 254; + public const int ERROR_INVALID_EVENT_COUNT = 151; + public const int ERROR_INVALID_EXE_SIGNATURE = 191; + public const int ERROR_INVALID_FLAG_NUMBER = 186; + public const int ERROR_INVALID_FUNCTION = 1; + public const int ERROR_INVALID_HANDLE = 6; + public const int ERROR_INVALID_LEVEL = 124; + public const int ERROR_INVALID_LIST_FORMAT = 153; + public const int ERROR_INVALID_LOCK_RANGE = 307; + public const int ERROR_INVALID_MINALLOCSIZE = 195; + public const int ERROR_INVALID_MODULETYPE = 190; + public const int ERROR_INVALID_NAME = 123; + public const int ERROR_INVALID_OPLOCK_PROTOCOL = 301; + public const int ERROR_INVALID_ORDINAL = 182; + public const int ERROR_INVALID_PARAMETER = 87; + public const int ERROR_INVALID_PASSWORD = 86; + public const int ERROR_INVALID_SEGDPL = 198; + public const int ERROR_INVALID_SEGMENT_NUMBER = 180; + public const int ERROR_INVALID_SIGNAL_NUMBER = 209; + public const int ERROR_INVALID_STACKSEG = 189; + public const int ERROR_INVALID_STARTING_CODESEG = 188; + public const int ERROR_INVALID_TARGET_HANDLE = 114; + public const int ERROR_INVALID_VERIFY_SWITCH = 118; + public const int ERROR_IOPL_NOT_ENABLED = 197; + public const int ERROR_IS_JOIN_PATH = 147; + public const int ERROR_IS_JOIN_TARGET = 133; + public const int ERROR_IS_JOINED = 134; + public const int ERROR_IS_SUBST_PATH = 146; + public const int ERROR_IS_SUBST_TARGET = 149; + public const int ERROR_IS_SUBSTED = 135; + public const int ERROR_ITERATED_DATA_EXCEEDS_64k = 194; + public const int ERROR_JOIN_TO_JOIN = 138; + public const int ERROR_JOIN_TO_SUBST = 140; + public const int ERROR_LABEL_TOO_LONG = 154; + public const int ERROR_LOCK_FAILED = 167; + public const int ERROR_LOCK_VIOLATION = 33; + public const int ERROR_LOCKED = 212; + public const int ERROR_MAX_SESSIONS_REACHED = 353; + public const int ERROR_MAX_THRDS_REACHED = 164; + public const int ERROR_META_EXPANSION_TOO_LONG = 208; + public const int ERROR_MOD_NOT_FOUND = 126; + public const int ERROR_MORE_DATA = 234; + public const int ERROR_MR_MID_NOT_FOUND = 317; + public const int ERROR_NEGATIVE_SEEK = 131; + public const int ERROR_NESTING_NOT_ALLOWED = 215; + public const int ERROR_NET_WRITE_FAULT = 88; + public const int ERROR_NETNAME_DELETED = 64; + public const int ERROR_NETWORK_ACCESS_DENIED = 65; + public const int ERROR_NETWORK_BUSY = 54; + public const int ERROR_NO_DATA = 232; + public const int ERROR_NO_MORE_FILES = 18; + public const int ERROR_NO_MORE_ITEMS = 259; + public const int ERROR_NO_MORE_SEARCH_HANDLES = 113; + public const int ERROR_NO_PROC_SLOTS = 89; + public const int ERROR_NO_SIGNAL_SENT = 205; + public const int ERROR_NO_SPOOL_SPACE = 62; + public const int ERROR_NO_VOLUME_LABEL = 125; + public const int ERROR_NOT_DOS_DISK = 26; + public const int ERROR_NOT_ENOUGH_MEMORY = 8; + public const int ERROR_NOT_JOINED = 136; + public const int ERROR_NOT_LOCKED = 158; + public const int ERROR_NOT_OWNER = 288; + public const int ERROR_NOT_READY = 21; + public const int ERROR_NOT_SAME_DEVICE = 17; + public const int ERROR_NOT_SUBSTED = 137; + public const int ERROR_NOT_SUPPORTED = 50; + public const int ERROR_NOTIFICATION_GUID_ALREADY_DEFINED = 309; + public const int ERROR_OPEN_FAILED = 110; + public const int ERROR_OPLOCK_NOT_GRANTED = 300; + public const int ERROR_OUT_OF_PAPER = 28; + public const int ERROR_OUT_OF_STRUCTURES = 84; + public const int ERROR_OUTOFMEMORY = 14; + public const int ERROR_PARTIAL_COPY = 299; + public const int ERROR_PATH_BUSY = 148; + public const int ERROR_PATH_NOT_FOUND = 3; + public const int ERROR_PIPE_BUSY = 231; + public const int ERROR_PIPE_LOCAL = 229; + public const int ERROR_PIPE_NOT_CONNECTED = 233; + public const int ERROR_PRINT_CANCELLED = 63; + public const int ERROR_PRINTQ_FULL = 61; + public const int ERROR_PROC_NOT_FOUND = 127; + public const int ERROR_PROCESS_MODE_ALREADY_BACKGROUND = 402; + public const int ERROR_PROCESS_MODE_NOT_BACKGROUND = 403; + public const int ERROR_READ_FAULT = 30; + public const int ERROR_REDIR_PAUSED = 72; + public const int ERROR_RELOC_CHAIN_XEEDS_SEGLIM = 201; + public const int ERROR_REM_NOT_LIST = 51; + public const int ERROR_REQ_NOT_ACCEP = 71; + public const int ERROR_RING2_STACK_IN_USE = 207; + public const int ERROR_RING2SEG_MUST_BE_MOVABLE = 200; + public const int ERROR_SAME_DRIVE = 143; + public const int ERROR_SCOPE_NOT_FOUND = 318; + public const int ERROR_SECTOR_NOT_FOUND = 27; + public const int ERROR_SECURITY_STREAM_IS_INCONSISTENT = 306; + public const int ERROR_SEEK_ON_DEVICE = 132; + public const int ERROR_SEEK = 25; + public const int ERROR_SEM_IS_SET = 102; + public const int ERROR_SEM_NOT_FOUND = 187; + public const int ERROR_SEM_OWNER_DIED = 105; + public const int ERROR_SEM_TIMEOUT = 121; + public const int ERROR_SEM_USER_LIMIT = 106; + public const int ERROR_SHARING_BUFFER_EXCEEDED = 36; + public const int ERROR_SHARING_PAUSED = 70; + public const int ERROR_SHARING_VIOLATION = 32; + public const int ERROR_SHORT_NAMES_NOT_ENABLED_ON_VOLUME = 305; + public const int ERROR_SIGNAL_PENDING = 162; + public const int ERROR_SIGNAL_REFUSED = 156; + public const int ERROR_SUBST_TO_JOIN = 141; + public const int ERROR_SUBST_TO_SUBST = 139; + public const int ERROR_SUCCESS = 0; + public const int ERROR_SYSTEM_TRACE = 150; + public const int ERROR_THREAD_1_INACTIVE = 210; + public const int ERROR_THREAD_MODE_ALREADY_BACKGROUND = 400; + public const int ERROR_THREAD_MODE_NOT_BACKGROUND = 401; + public const int ERROR_TOO_MANY_CMDS = 56; + public const int ERROR_TOO_MANY_MODULES = 214; + public const int ERROR_TOO_MANY_MUXWAITERS = 152; + public const int ERROR_TOO_MANY_NAMES = 68; + public const int ERROR_TOO_MANY_OPEN_FILES = 4; + public const int ERROR_TOO_MANY_POSTS = 298; + public const int ERROR_TOO_MANY_SEM_REQUESTS = 103; + public const int ERROR_TOO_MANY_SEMAPHORES = 100; + public const int ERROR_TOO_MANY_SESS = 69; + public const int ERROR_TOO_MANY_TCBS = 155; + public const int ERROR_UNEXP_NET_ERR = 59; + public const int ERROR_VC_DISCONNECTED = 240; + public const int ERROR_VIRUS_DELETED = 226; + public const int ERROR_VIRUS_INFECTED = 225; + public const int ERROR_WAIT_NO_CHILDREN = 128; + public const int ERROR_WRITE_FAULT = 29; + public const int ERROR_WRITE_PROTECT = 19; + public const int ERROR_WRONG_DISK = 34; + public const int WAIT_TIMEOUT = 258; + + /// + /// Formats to a message + /// + /// ErrorCode + /// Message or "Unknown" if is not handles + public static string FormatMessage(int errorCode) + { + switch (errorCode) + { + case 0: return "The operation completed successfully."; + case 1: return "Incorrect function."; + case 10: return "The environment is incorrect."; + case 100: return "Cannot create another system semaphore."; + case 101: return "The exclusive semaphore is owned by another process."; + case 102: return "The semaphore is set and cannot be closed."; + case 103: return "The semaphore cannot be set again."; + case 104: return "Cannot request exclusive semaphores at interrupt time."; + case 105: return "The previous ownership of this semaphore has ended."; + case 106: return "Insert the diskette for drive %1."; + case 107: return "The program stopped because an alternate diskette was not inserted."; + case 108: return "The disk is in use or locked by another process."; + case 109: return "The pipe has been ended."; + case 11: return "An attempt was made to load a program with an incorrect format."; + case 110: return "The system cannot open the device or file specified."; + case 111: return "The file name is too long."; + case 112: return "There is not enough space on the disk."; + case 113: return "No more internal file identifiers available."; + case 114: return "The target internal file identifier is incorrect."; + case 117: return "The IOCTL call made by the application program is not correct."; + case 118: return "The verify-on-write switch parameter value is not correct."; + case 119: return "The system does not support the command requested."; + case 12: return "The access code is invalid."; + case 120: return "This function is not supported on this system."; + case 121: return "The semaphore timeout period has expired."; + case 122: return "The data area passed to a system call is too small."; + case 123: return "The filename, directory name, or volume label syntax is incorrect."; + case 124: return "The system call level is not correct."; + case 125: return "The disk has no volume label."; + case 126: return "The specified module could not be found."; + case 127: return "The specified procedure could not be found."; + case 128: return "There are no child processes to wait for."; + case 129: return "The %1 application cannot be run in Win32 mode."; + case 13: return "The data is invalid."; + case 130: return "Attempt to use a file handle to an open disk partition for an operation other than raw disk I/O."; + case 131: return "An attempt was made to move the file pointer before the beginning of the file."; + case 132: return "The file pointer cannot be set on the specified device or file."; + case 133: return "A JOIN or SUBST command cannot be used for a drive that contains previously joined drives."; + case 134: return "An attempt was made to use a JOIN or SUBST command on a drive that has already been joined."; + case 135: return "An attempt was made to use a JOIN or SUBST command on a drive that has already been substituted."; + case 136: return "The system tried to delete the JOIN of a drive that is not joined."; + case 137: return "The system tried to delete the substitution of a drive that is not substituted."; + case 138: return "The system tried to join a drive to a directory on a joined drive."; + case 139: return "The system tried to substitute a drive to a directory on a substituted drive."; + case 14: return "Not enough storage is available to complete this operation."; + case 140: return "The system tried to join a drive to a directory on a substituted drive."; + case 141: return "The system tried to SUBST a drive to a directory on a joined drive."; + case 142: return "The system cannot perform a JOIN or SUBST at this time."; + case 143: return "The system cannot join or substitute a drive to or for a directory on the same drive."; + case 144: return "The directory is not a subdirectory of the root directory."; + case 145: return "The directory is not empty."; + case 146: return "The path specified is being used in a substitute."; + case 147: return "Not enough resources are available to process this command."; + case 148: return "The path specified cannot be used at this time."; + case 149: return "An attempt was made to join or substitute a drive for which a directory on the drive is the target of a previous substitute."; + case 15: return "The system cannot find the drive specified."; + case 150: return "System trace information was not specified in your CONFIG.SYS file, or tracing is disallowed."; + case 151: return "The number of specified semaphore events for DosMuxSemWait is not correct."; + case 152: return "DosMuxSemWait did not execute; too many semaphores are already set."; + case 153: return "The DosMuxSemWait list is not correct."; + case 154: return "The volume label you entered exceeds the label character limit of the target file system."; + case 155: return "Cannot create another thread."; + case 156: return "The recipient process has refused the signal."; + case 157: return "The segment is already discarded and cannot be locked."; + case 158: return "The segment is already unlocked."; + case 159: return "The address for the thread ID is not correct."; + case 16: return "The directory cannot be removed."; + case 160: return "One or more arguments are not correct."; + case 161: return "The specified path is invalid."; + case 162: return "A signal is already pending."; + case 164: return "No more threads can be created in the system."; + case 167: return "Unable to lock a region of a file."; + case 17: return "The system cannot move the file to a different disk drive."; + case 170: return "The requested resource is in use."; + case 173: return "A lock request was not outstanding for the supplied cancel region."; + case 174: return "The file system does not support atomic changes to the lock type."; + case 18: return "There are no more files."; + case 180: return "The system detected a segment number that was not correct."; + case 182: return "The operating system cannot run %1."; + case 183: return "Cannot create a file when that file already exists."; + case 186: return "The flag passed is not correct."; + case 187: return "The specified system semaphore name was not found."; + case 188: return "The operating system cannot run %1."; + case 189: return "The operating system cannot run %1."; + case 19: return "The media is write protected."; + case 190: return "The operating system cannot run %1."; + case 191: return "Cannot run %1 in Win32 mode."; + case 192: return "The operating system cannot run %1."; + case 193: return "is not a valid Win32 application."; + case 194: return "The operating system cannot run %1."; + case 195: return "The operating system cannot run %1."; + case 196: return "The operating system cannot run this application program."; + case 197: return "The operating system is not presently configured to run this application."; + case 198: return "The operating system cannot run %1."; + case 199: return "The operating system cannot run this application program."; + case 2: return "The system cannot find the file specified."; + case 20: return "The system cannot find the device specified."; + case 200: return "The code segment cannot be greater than or equal to 64K."; + case 201: return "The operating system cannot run %1."; + case 202: return "The operating system cannot run %1."; + case 203: return "The system could not find the environment option that was entered."; + case 205: return "No process in the command subtree has a signal handler."; + case 206: return "The filename or extension is too long."; + case 207: return "The ring 2 stack is in use."; + case 208: return "The global filename characters, * or ?, are entered incorrectly or too many global filename characters are specified."; + case 209: return "The signal being posted is not correct."; + case 21: return "The device is not ready."; + case 210: return "The signal handler cannot be set."; + case 212: return "The segment is locked and cannot be reallocated."; + case 214: return "Too many dynamic-link modules are attached to this program or dynamic-link module."; + case 215: return "Cannot nest calls to LoadModule."; + case 216: return "The version of %1 is not compatible with the version you're running. Check your computer's system information to see whether you need a x86 ; or x64 ; version of the program, and then contact the software publisher."; + case 217: return "The image file %1 is signed, unable to modify."; + case 218: return "The image file %1 is strong signed, unable to modify."; + case 22: return "The device does not recognize the command."; + case 220: return "This file is checked out or locked for editing by another user."; + case 221: return "The file must be checked out before saving changes."; + case 222: return "The file type being saved or retrieved has been blocked."; + case 223: return "The file size exceeds the limit allowed and cannot be saved."; + case 224: return "Access Denied. Before opening files in this location, you must first add the web site to your trusted sites list, browse to the web site, and select the option to login automatically."; + case 225: return "Operation did not complete successfully because the file contains a virus."; + case 226: return "This file contains a virus and cannot be opened. Due to the nature of this virus, the file has been removed from this location."; + case 229: return "The pipe is local."; + case 23: return "Data error ;."; + case 230: return "The pipe state is invalid."; + case 231: return "All pipe instances are busy."; + case 232: return "The pipe is being closed."; + case 233: return "No process is on the other end of the pipe."; + case 234: return "More data is available."; + case 24: return "The program issued a command but the command length is incorrect."; + case 240: return "The session was canceled."; + case 25: return "The drive cannot locate a specific area or track on the disk."; + case 254: return "The specified extended attribute name was invalid."; + case 255: return "The extended attributes are inconsistent."; + case 258: return "The wait operation timed out."; + case 259: return "No more data is available."; + case 26: return "The specified disk or diskette cannot be accessed."; + case 266: return "The copy functions cannot be used."; + case 267: return "The directory name is invalid."; + case 27: return "The drive cannot find the sector requested."; + case 275: return "The extended attributes did not fit in the buffer."; + case 276: return "The extended attribute file on the mounted file system is corrupt."; + case 277: return "The extended attribute table file is full."; + case 278: return "The specified extended attribute handle is invalid."; + case 28: return "The printer is out of paper."; + case 282: return "The mounted file system does not support extended attributes."; + case 288: return "Attempt to release mutex not owned by caller."; + case 29: return "The system cannot write to the specified device."; + case 298: return "Too many posts were made to a semaphore."; + case 299: return "Only part of a ReadProcessMemory or WriteProcessMemory request was completed."; + case 3: return "The system cannot find the path specified."; + case 30: return "The system cannot read from the specified device."; + case 300: return "The oplock request is denied."; + case 301: return "An invalid oplock acknowledgment was received by the system."; + case 302: return "The volume is too fragmented to complete this operation."; + case 303: return "The file cannot be opened because it is in the process of being deleted."; + case 304: return "Short name settings may not be changed on this volume due to the global registry setting."; + case 305: return "Short names are not enabled on this volume."; + case 306: return "The security stream for the given volume is in an inconsistent state. Please run CHKDSK on the volume."; + case 307: return "A requested file lock operation cannot be processed due to an invalid byte range."; + case 308: return "The subsystem needed to support the image type is not present."; + case 309: return "The specified file already has a notification GUID associated with it."; + case 31: return "A device attached to the system is not functioning."; + case 317: return "The system cannot find message text for message number 0x%1 in the message file for %2."; + case 318: return "The scope specified was not found."; + case 32: return "The process cannot access the file because it is being used by another process."; + case 33: return "The process cannot access the file because another process has locked a portion of the file."; + case 34: return "The wrong diskette is in the drive. Insert %2 ; into drive %1."; + case 350: return "No action was taken as a system reboot is required."; + case 351: return "The shutdown operation failed."; + case 352: return "The restart operation failed."; + case 353: return "The maximum number of sessions has been reached."; + case 36: return "Too many files opened for sharing."; + case 38: return "Reached the end of the file."; + case 39: return "The disk is full."; + case 4: return "The system cannot open the file."; + case 400: return "The thread is already in background processing mode."; + case 401: return "The thread is not in background processing mode."; + case 402: return "The process is already in background processing mode."; + case 403: return "The process is not in background processing mode."; + case 487: return "Attempt to access invalid address."; + case 5: return "Access is denied."; + case 50: return "The request is not supported."; + case 51: return "Windows cannot find the network path. Verify that the network path is correct and the destination computer is not busy or turned off. If Windows still cannot find the network path, contact your network administrator."; + case 52: return "You were not connected because a duplicate name exists on the network. If joining a domain, go to System in Control Panel to change the computer name and try again. If joining a workgroup, choose another workgroup name."; + case 53: return "The network path was not found."; + case 54: return "The network is busy."; + case 55: return "The specified network resource or device is no longer available."; + case 56: return "The network BIOS command limit has been reached."; + case 57: return "A network adapter hardware error occurred."; + case 58: return "The specified server cannot perform the requested operation."; + case 59: return "An unexpected network error occurred."; + case 6: return "The handle is invalid."; + case 60: return "The remote adapter is not compatible."; + case 61: return "The printer queue is full."; + case 62: return "Space to store the file waiting to be printed is not available on the server."; + case 63: return "Your file waiting to be printed was deleted."; + case 64: return "The specified network name is no longer available."; + case 65: return "Network access is denied."; + case 66: return "The network resource type is not correct."; + case 67: return "The network name cannot be found."; + case 68: return "The name limit for the local computer network adapter card was exceeded."; + case 69: return "The network BIOS session limit was exceeded."; + case 7: return "The storage control blocks were destroyed."; + case 70: return "The remote server has been paused or is in the process of being started."; + case 71: return "No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept."; + case 72: return "The specified printer or disk device has been paused."; + case 8: return "Not enough storage is available to process this command."; + case 80: return "The file exists."; + case 82: return "The directory or file cannot be created."; + case 83: return "Fail on INT 24."; + case 84: return "Storage to process this request is not available."; + case 85: return "The local device name is already in use."; + case 86: return "The specified network password is not correct."; + case 87: return "The parameter is incorrect."; + case 88: return "A write fault occurred on the network."; + case 89: return "The system cannot start another process at this time."; + case 9: return "The storage control block address is invalid."; + + default: return "unknown."; + } + } +} diff --git a/src/QuickIO/Win32API/Win32FileHandle.cs b/src/QuickIO/Win32API/Win32FileHandle.cs new file mode 100644 index 0000000..1eb6223 --- /dev/null +++ b/src/QuickIO/Win32API/Win32FileHandle.cs @@ -0,0 +1,50 @@ +using Microsoft.Win32.SafeHandles; + +namespace SchwabenCode.QuickIO.Win32API; + +/// +/// Provides a class for Win32 safe handle implementations +/// +internal sealed class Win32FileHandle : SafeHandleZeroOrMinusOneIsInvalid +{ + /// + /// Initializes a new instance of the Win32ApiFileHandle class, specifying whether the handle is to be reliably released. + /// + internal Win32FileHandle() + : base(true) + { + } + + /// + /// Initializes a new instance of the Win32ApiFileHandle class, specifying whether the handle is to be reliably released. + /// + public Win32FileHandle(IntPtr preExistingHandle, bool ownsHandle) + : base(ownsHandle) + { + base.SetHandle(preExistingHandle); + } + + /// + /// When overridden in a derived class, executes the code required to free the handle. + /// + protected override bool ReleaseHandle() + { + if (!(IsInvalid || IsClosed)) + { + return Win32SafeNativeMethods.FindClose(this); + } + return (IsInvalid || IsClosed); + } + + /// + /// Releases the unmanaged resources used by the Win32ApiFileHandle class specifying whether to perform a normal dispose operation. + /// + protected override void Dispose(bool disposing) + { + if (!(IsInvalid || IsClosed)) + { + _ = Win32SafeNativeMethods.FindClose(this); + } + base.Dispose(disposing); + } +} diff --git a/src/QuickIO/Win32API/Win32FileSystemEntrySecurityInformation.cs b/src/QuickIO/Win32API/Win32FileSystemEntrySecurityInformation.cs new file mode 100644 index 0000000..41ce42f --- /dev/null +++ b/src/QuickIO/Win32API/Win32FileSystemEntrySecurityInformation.cs @@ -0,0 +1,20 @@ +namespace SchwabenCode.QuickIO.Win32API; + +/// +/// Win32 Security Information +/// +[Flags] +internal enum Win32FileSystemEntrySecurityInformation : uint +{ + OwnerSecurityInformation = 1, + GroupSecurityInformation = 2, + + DaclSecurityInformation = 4, + SaclSecurityInformation = 8, + + UnprotectedSaclSecurityInformation = 0x10000000, + UnprotectedDaclSecurityInformation = 0x20000000, + + ProtectedSaclSecurityInformation = 0x40000000, + ProtectedDaclSecurityInformation = 0x80000000 +} diff --git a/src/QuickIO/Win32API/Win32FileTime.cs b/src/QuickIO/Win32API/Win32FileTime.cs new file mode 100644 index 0000000..ccb2788 --- /dev/null +++ b/src/QuickIO/Win32API/Win32FileTime.cs @@ -0,0 +1,14 @@ +using System.Runtime.InteropServices; + +namespace SchwabenCode.QuickIO.Win32API; + +/// +/// See http://www.pinvoke.net/default.aspx/Structures/FILETIME.html?diff=y +/// Represents Win32 LongFileTime +/// +[StructLayout(LayoutKind.Sequential)] +internal struct Win32FileTime +{ + public uint DateTimeLow; + public uint DateTimeHigh; +} diff --git a/src/QuickIO/Win32API/Win32FindData.cs b/src/QuickIO/Win32API/Win32FindData.cs new file mode 100644 index 0000000..ece24bc --- /dev/null +++ b/src/QuickIO/Win32API/Win32FindData.cs @@ -0,0 +1,112 @@ +using System.Runtime.InteropServices; +using SchwabenCode.QuickIO.Internal; + +namespace SchwabenCode.QuickIO.Win32API; + +/// +/// Structure of File Data given by Win32 API +/// +[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] +[BestFitMapping(false)] +internal class Win32FindData +{ + /// + /// File Attributes + /// + public FileAttributes dwFileAttributes; + + /// + /// Last Creation Time (Low DateTime) + /// + public uint ftCreationTime_dwLowDateTime; + + /// + /// Last Creation Time (High DateTime) + /// + public uint ftCreationTime_dwHighDateTime; + + /// + /// Last Access Time (Low DateTime) + /// + public uint ftLastAccessTime_dwLowDateTime; + + /// + /// Last Access Time (High DateTime) + /// + public uint ftLastAccessTime_dwHighDateTime; + + /// + /// Last Write Time (Low DateTime) + /// + public uint ftLastWriteTime_dwLowDateTime; + + /// + /// Last Write Time (High DateTime) + /// + public uint ftLastWriteTime_dwHighDateTime; + + /// + /// File Size High + /// + public uint nFileSizeHigh; + + /// + /// File Size Low + /// + public uint nFileSizeLow; + + /// + /// Reserved + /// + public int dwReserved0; + + /// + /// Reserved + /// + public int dwReserved1; + + /// + /// File name + /// + [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 260 )] + public string cFileName = null!; + + /// + /// Alternate File Name + /// + [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 14 )] + public string cAlternateFileName = null!; + + /// + /// Creates a new Instance + /// + public static Win32FindData New => new(); + + /// + /// Returns the total size in bytes + /// + /// + public ulong CalculateBytes() + => (ulong)nFileSizeHigh << 32 | nFileSizeLow; + + /// + /// Gets last write time based on UTC + /// + /// + public DateTime GetLastWriteTimeUtc() + => InternalRawDataHelpers.ConvertDateTime(ftLastWriteTime_dwHighDateTime, ftLastWriteTime_dwLowDateTime); + + /// + /// Gets last access time based on UTC + /// + /// + public DateTime GetLastAccessTimeUtc() + => InternalRawDataHelpers.ConvertDateTime(ftLastAccessTime_dwHighDateTime, ftLastAccessTime_dwLowDateTime); + + /// + /// Gets the creation time based on UTC + /// + /// + public DateTime GetCreationTimeUtc() + => InternalRawDataHelpers.ConvertDateTime(ftCreationTime_dwHighDateTime, ftCreationTime_dwLowDateTime); +} diff --git a/src/QuickIO/Win32API/Win32SafeNativeMethods.cs b/src/QuickIO/Win32API/Win32SafeNativeMethods.cs new file mode 100644 index 0000000..599f8e9 --- /dev/null +++ b/src/QuickIO/Win32API/Win32SafeNativeMethods.cs @@ -0,0 +1,219 @@ +using System.Runtime.InteropServices; +using System.Text; +using Microsoft.Win32.SafeHandles; + +namespace SchwabenCode.QuickIO.Win32API; + +/// +/// Native Methods - take a look on www.pinvoke.net +/// +internal static class Win32SafeNativeMethods +{ + #region advapi32.dll + [DllImport("advapi32.dll", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)] + internal static extern uint GetSecurityDescriptorLength(IntPtr byteArray); + + + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern uint SetNamedSecurityInfo( + string unicodePath, + Win32SecurityObjectType objectType, + Win32FileSystemEntrySecurityInformation securityInfo, + IntPtr sidOwner, + IntPtr sidGroup, + IntPtr dacl, + IntPtr sacl); + + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern uint GetNamedSecurityInfo( + string unicodePath, + Win32SecurityObjectType securityObjectType, + Win32FileSystemEntrySecurityInformation securityInfo, + out IntPtr sidOwner, + out IntPtr sidGroup, + out IntPtr dacl, + out IntPtr sacl, + out IntPtr securityDescriptor); + + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern bool ConvertStringSidToSid(string sidString, ref IntPtr sidHandle); + + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern uint LookupAccountSid(string systemName, IntPtr sidHandle, StringBuilder name, ref int cchName, StringBuilder domainName, ref int cchDomainName, out int peUse); + + #endregion + + #region kernel32.dll + + /// + /// Sets the last all times for files or directories + /// + [DllImport("kernel32.dll", SetLastError = true, EntryPoint = "SetFileTime", ExactSpelling = true)] + internal static extern int SetAllFileTimes(SafeFileHandle fileHandle, ref long lpCreationTime, ref long lpLastAccessTime, ref long lpLastWriteTime); + + /// + /// Sets the last creation time for files or directories + /// + [DllImport("kernel32.dll", SetLastError = true, EntryPoint = "SetFileTime", ExactSpelling = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetCreationFileTime(SafeFileHandle hFile, ref long lpCreationTime, IntPtr lpLastAccessTime, IntPtr lpLastWriteTime); + + /// + /// Sets the last acess time for files or directories + /// + [DllImport("kernel32.dll", SetLastError = true, EntryPoint = "SetFileTime", ExactSpelling = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetLastAccessFileTime(SafeFileHandle hFile, IntPtr lpCreationTime, ref long lpLastAccessTime, IntPtr lpLastWriteTime); + + /// + /// Sets the last write time for files or directories + /// + [DllImport("kernel32.dll", SetLastError = true, EntryPoint = "SetFileTime", ExactSpelling = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SetLastWriteFileTime(SafeFileHandle hFile, IntPtr lpCreationTime, IntPtr lpLastAccessTime, ref long lpLastWriteTime); + + /// + /// Create directory + /// + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool CreateDirectory(string fullName, IntPtr securityAttributes); + + /// + /// Creates a file / directory or opens an handle for an existing file. + /// If you want to get an handle for an existing folder use with ( 0x02000000 ) as attribute and FileMode ( 0x40000000 | 0x80000000 ) + /// Otherwise it you'll get an invalid handle + /// + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern SafeFileHandle CreateFile( + string fullName, + [MarshalAs(UnmanagedType.U4)] FileAccess dwDesiredAccess, + [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, + IntPtr lpSecurityAttributes, + [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition, + [MarshalAs(UnmanagedType.U4)] FileAttributes dwFlagsAndAttributes, + IntPtr hTemplateFile); + + /// + /// Use this to open an handle for an existing file or directory to change for example the timestamps + /// + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateFile")] + internal static extern SafeFileHandle OpenReadWriteFileSystemEntryHandle( + string fullName, + uint dwAccess, + [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, + IntPtr lpSecurityAttributes, + [MarshalAs(UnmanagedType.U4)] FileMode dwMode, + uint dwAttribute, + IntPtr hTemplateFile); + + /// + /// Open handle for appending + ///
+ /// FileMode has to be 0x0004 for internal appending mode + ///
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateFile")] + internal static extern SafeFileHandle CreateFileForAppend( + string fullName, + [MarshalAs(UnmanagedType.U4)] uint dwDesiredAccess, + [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, + IntPtr lpSecurityAttributes, + [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition, + [MarshalAs(UnmanagedType.U4)] FileAttributes dwFlagsAndAttributes, + IntPtr hTemplateFile); + + /// + /// Finds first file of given path + /// + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern Win32FileHandle FindFirstFile(string fullName, [In, Out] Win32FindData win32FindData); + + /// + /// Finds next file of current handle + /// + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern bool FindNextFile(Win32FileHandle findFileHandle, [In, Out, MarshalAs(UnmanagedType.LPStruct)] Win32FindData win32FindData); + + /// + /// Moves a directory + /// + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool MoveFile(string fullNameSource, string fullNameTarget); + + /// + /// Copy file + /// + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool CopyFile(string fullNameSource, string fullNameTarget, bool failOnExists); + + /// + /// Removes a file. + /// + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool DeleteFile(string fullName); + + /// + /// Removes a file. + /// + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool RemoveDirectory(string fullName); + + /// + /// Set File Attributes + /// + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern bool SetFileAttributes(string fullName, uint fileAttributes); + + /// + /// Gets Attributes of given path + /// + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern uint GetFileAttributes(string fullName); + + /// + /// Close Hnalde + /// + [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)] + internal static extern bool FindClose(SafeHandle fileHandle); + + /// + /// Free unmanaged memory + /// + [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)] + internal static extern IntPtr LocalFree(IntPtr handle); + + /// + /// QuickIOShareInfo information + /// + /// + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool GetDiskFreeSpaceEx(string uncPath, + out ulong freeBytes, + out ulong totalBytes, + out ulong totalFreeBytes); + #endregion + + #region netapi32.dll + /// + /// Enumerate shares (NT) + /// + /// http://msdn.microsoft.com/en-us/library/windows/desktop/bb525387(v=vs.85).aspx + [DllImport("netapi32", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern int NetShareEnum( + string lpServerName, + int dwLevel, + out IntPtr lpBuffer, + int dwPrefMaxLen, + out int entriesRead, + out int totalEntries, + ref int hResume); + + [DllImport("netapi32", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern int NetApiBufferFree(IntPtr lpBuffer); + #endregion +} diff --git a/src/QuickIO/Win32API/Win32SecurityObjectType.cs b/src/QuickIO/Win32API/Win32SecurityObjectType.cs new file mode 100644 index 0000000..b5c8c00 --- /dev/null +++ b/src/QuickIO/Win32API/Win32SecurityObjectType.cs @@ -0,0 +1,21 @@ +namespace SchwabenCode.QuickIO.Win32API; + +/// +/// Win32 Security Object Type +/// +internal enum Win32SecurityObjectType +{ + SeUnknownObjectType = 0x0, + SeFileObject = 0x1, + SeService = 0x2, + SePrinter = 0x3, + SeRegistryKey = 0x4, + SeLmshare = 0x5, + SeKernelObject = 0x6, + SeWindowObject = 0x7, + SeDsObject = 0x8, + SeDsObjectAll = 0x9, + SeProviderDefinedObject = 0xa, + SeWmiguidObject = 0xb, + SeRegistryWow6432Key = 0xc +} diff --git a/src/SchwabenCode.QuickIO/Engine/InternalEnumerateFileSystem.cs b/src/SchwabenCode.QuickIO/Engine/InternalEnumerateFileSystem.cs deleted file mode 100644 index fe2fd2a..0000000 --- a/src/SchwabenCode.QuickIO/Engine/InternalEnumerateFileSystem.cs +++ /dev/null @@ -1,300 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.IO; -using System.Linq; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO.Engine -{ - internal static class InternalEnumerateFileSystem - { - - /// - /// Search Exection - /// - /// Start directory path - /// Search pattern. Uses Win32 native filtering. - /// - /// The enumeration options for exception handling - /// Specifies the type of path to return. - /// - /// Collection of path - /// This error is fired if the specified path or a part of them does not exist. - public static IEnumerable EnumerateSystemPaths( String uncDirectoryPath, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOFileSystemEntryType? filterType = null ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( uncDirectoryPath ) ); - Contract.Ensures( Contract.Result>() != null ); - - - IEnumerable entries = EnumerateFileSystemEntries( uncDirectoryPath, pattern, searchOption, enumerateOptions ); - - // filter? - if( filterType != null ) - { - entries = entries.Where( entry => entry.Type == filterType ); - } - - // TODO: path format - - return entries.Select( entry => entry.Path ); - } - - /// - /// Determined all sub system entries of a directory - /// - /// Path of the directory - /// Search pattern. Uses Win32 native filtering. - /// - /// The enumeration options for exception handling - /// Collection of - /// This error is fired if the specified path or a part of them does not exist. - internal static IEnumerable EnumerateFileSystemEntries( String uncDirectoryPath, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( uncDirectoryPath ) ); - Contract.Ensures( Contract.Result>() != null ); - - return - ( from pair in EnumerateWin32FileSystemEntries( uncDirectoryPath, pattern, searchOption, enumerateOptions ) - let parentDirectory = pair.Item1 - let win32Entry = pair.Item2 - let fullpath = QuickIOPath.Combine( parentDirectory, win32Entry.Name ) - select - new QuickIOFileSystemEntry( fullpath, win32Entry.FileSystemEntryType, win32Entry.Attributes, win32Entry.Bytes ) ); - } - - /// - /// Determined all sub system entries of a directory - /// - /// Path of the directory - /// Search pattern. Uses Win32 native filtering. - /// - /// The enumeration options for exception handling - /// Collection of - /// This error is fired if the specified path or a part of them does not exist. - internal static IEnumerable> EnumerateWin32FileSystemEntries( String path, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( Contract.Result>>() != null ); - - // Stack - Stack directoryPathStack = new Stack(); - directoryPathStack.Push( path ); - - while( directoryPathStack.Count > 0 ) - { - string currentDirectory = directoryPathStack.Pop(); - - foreach( Win32FileSystemEntry systemEntry in new Win32FileHandleCollection( QuickIOPath.Combine( currentDirectory, pattern ) ) ) - { - yield return new Tuple( currentDirectory, systemEntry ); - - // Create hit for current search result - string resultPath = QuickIOPath.Combine( currentDirectory, systemEntry.Name ); - - // Check for Directory - if( searchOption == SearchOption.AllDirectories && systemEntry.IsDirectory ) - { - directoryPathStack.Push( resultPath ); - } - } - } - } - - - /// - /// Determined metadata of directory - /// - /// Path of the directory - /// The enumeration options for exception handling - /// started with the given directory - /// This error is fired if the specified path or a part of them does not exist. - internal static QuickIODirectoryMetadata EnumerateDirectoryMetadata( String path, QuickIOEnumerateOptions enumerateOptions ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( Contract.Result() != null ); - - IList entries = - new Win32FileHandleCollection( path ).Cast().ToList(); - - // TODO: search another solution instead of enumerator - if( entries.Count > 1 ) - { - throw new InvalidOperationException( "Found more than one entry to one specific path." ); - } - - return EnumerateDirectoryMetadata( path, entries.ElementAt( 0 ), enumerateOptions ); ; - } - /// - /// Determined metadata of directory - /// - /// Path of the directory - /// - /// The enumeration options for exception handling - /// started with the given directory - /// This error is fired if the specified path or a part of them does not exist. - private static QuickIODirectoryMetadata EnumerateDirectoryMetadata( String path, Win32FileSystemEntry fileSystemEntry, QuickIOEnumerateOptions enumerateOptions ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( Contract.Result() != null ); - - // Results - IList subFiles = new List(); - IList subDirs = new List(); - - - foreach( Win32FileSystemEntry systemEntry in new Win32FileHandleCollection( QuickIOPath.Combine( path, QuickIOPatterns.PathMatchAll ) ) ) - { - // Create hit for current search result - var uncResultPath = QuickIOPath.Combine( path, systemEntry.Name ); - - // if it's a file, add to the collection - if( systemEntry.IsFile ) - { - subFiles.Add( new QuickIOFileMetadata( uncResultPath, systemEntry.FindData ) ); - } - else - { - - subDirs.Add( EnumerateDirectoryMetadata( uncResultPath, systemEntry, enumerateOptions ) ); - } - } - return new QuickIODirectoryMetadata( path, fileSystemEntry.FindData, subDirs, subFiles ); - } - - - /// - /// Determined all files of a directory - /// - /// Path of the directory - /// Search pattern. Uses Win32 native filtering. - /// - /// The enumeration options for exception handling - /// Collection of files - /// This error is fired if the specified path or a part of them does not exist. - internal static IEnumerable EnumerateFiles( String uncDirectoryPath, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( uncDirectoryPath ) ); - Contract.Ensures( Contract.Result>() != null ); - - foreach( Win32FileSystemEntry systemEntry in new Win32FileHandleCollection( QuickIOPath.Combine( uncDirectoryPath, pattern ) ) ) - { - // Create hit for current search result - var resultPath = QuickIOPath.Combine( uncDirectoryPath, systemEntry.Name ); - - // Check for Directory - if( systemEntry.IsFile ) - { - yield return new QuickIOFileInfo( resultPath, systemEntry.FindData ); - } - else if(/* it's already a directory here */ searchOption == SearchOption.AllDirectories ) - { - foreach( var match in EnumerateFiles( resultPath, pattern, searchOption, enumerateOptions ) ) - { - yield return match; - } - } - - } - - } - - /// - /// Determined all subfolders of a directory - /// - /// Path of the directory - /// Search pattern. Uses Win32 native filtering. - /// - /// The enumeration options for exception handling - /// collection of subfolders - /// This error is fired if the specified path or a part of them does not exist. - internal static IEnumerable EnumerateDirectories( string uncDirectoryPath, - String pattern = QuickIOPatterns.PathMatchAll, - SearchOption searchOption = SearchOption.TopDirectoryOnly, - QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( uncDirectoryPath ) ); - Contract.Ensures( Contract.Result>() != null ); - - // Stack - Stack directoryPathStack = new Stack(); - directoryPathStack.Push( uncDirectoryPath ); - - while( directoryPathStack.Count > 0 ) - { - string currentDirectory = directoryPathStack.Pop(); - - foreach( Win32FileSystemEntry systemEntry in new Win32FileHandleCollection( QuickIOPath.Combine( currentDirectory, pattern ) ) ) - { - // Create hit for current search result - var resultPath = QuickIOPath.Combine( currentDirectory, systemEntry.Name ); - - // Check for Directory - if( systemEntry.IsDirectory ) - { - yield return new QuickIODirectoryInfo( resultPath, systemEntry.FindData ); - - // SubFolders?! - if( searchOption == SearchOption.AllDirectories ) - { - directoryPathStack.Push( resultPath ); - } - } - } - } - } - - - /// - /// Determines the statistics of the given directory. This includes the number of files, folders and the total size in bytes. - /// - /// Path to the directory to generate the statistics. - /// Provides the statistics of the directory - /// This error is fired if the specified path or a part of them does not exist. - public static QuickIOFolderStatisticResult EnumerateDirectoryStatistics( String uncDirectoryPath ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( uncDirectoryPath ) ); - Contract.Ensures( Contract.Result() != null ); - - UInt64 fileCount = 0; - UInt64 folderCount = 0; - UInt64 totalSize = 0; - - Stack < string> directoryPathStack = new Stack(); - directoryPathStack.Push( uncDirectoryPath ); - - while( directoryPathStack.Count > 0 ) - { - folderCount++; - - string currentDirectory = directoryPathStack.Pop(); - foreach( Win32FileSystemEntry systemEntry in new Win32FileHandleCollection( QuickIOPath.Combine( currentDirectory, QuickIOPatterns.PathMatchAll ) ) ) - { - - // Create hit for current search result - var resultPath = QuickIOPath.Combine( currentDirectory, systemEntry.Name ); - - // if it's a file, add to the collection - if( systemEntry.IsFile ) - { - fileCount++; - totalSize += systemEntry.Bytes; - } - else - { - directoryPathStack.Push( resultPath ); - } - } - } - - - // Return result; - return new QuickIOFolderStatisticResult( folderCount, fileCount, totalSize ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.Directories.cs b/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.Directories.cs deleted file mode 100644 index 32c8fcf..0000000 --- a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.Directories.cs +++ /dev/null @@ -1,119 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Runtime.InteropServices; -using System.Security.Permissions; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO.Engine -{ - /// - /// Provides internal methods. PathMatchAll IO operations are called from here. - /// - [FileIOPermission( SecurityAction.Demand, AllFiles = FileIOPermissionAccess.AllAccess, AllLocalFiles = FileIOPermissionAccess.AllAccess )] - internal static partial class QuickIOEngine - { - - /// - /// Creates a new directory. If is false, the parent directory must exists. - /// - /// Directory path - /// If is false, the parent directory must exist. - /// The specified path already exists. - /// This error is fired if the specified path or a part of them does not exist. - public static void CreateDirectory( string uncDirectoryPath, bool recursive = false ) - { - Contract.Requires( !String.IsNullOrEmpty( uncDirectoryPath ) ); - - // cancel if path exists - if( Exists( uncDirectoryPath ) ) - { - return; - } - - // cancel if requested path is root - if( QuickIOPath.IsRoot( uncDirectoryPath ) ) - { - throw new InvalidOperationException( "A root directory cannot be created." ); - } - - // create parent directory if accepted - if( recursive ) - { - string parent = QuickIOPath.GetDirectoryName( uncDirectoryPath ); - if( parent == null ) - { - throw new InvalidOperationException( "Parent directory does not exists and cannot be created." ); - } - - Stack stack = new Stack(); - stack.Push( parent ); - - while( stack.Count > 0 ) - { - string currentDirectory = stack.Pop(); - - if( QuickIOPath.IsRoot( currentDirectory ) ) - { - if( !QuickIOPath.Exists( currentDirectory ) ) - { - throw new InvalidOperationException( "A root directory cannot be created." ); - } - } - else - { - // no root path here - if( !Win32SafeNativeMethods.CreateDirectory( currentDirectory, IntPtr.Zero ) ) - { - Win32ErrorCodes.NativeExceptionMapping( currentDirectory, Marshal.GetLastWin32Error() ); - } - } - } - } - } - - /// - /// Deletes the given directory. On request all contents, too. - /// - /// Path of directory to delete - /// If is true then all subfolders are also deleted. - /// This error is fired if the specified path or a part of them does not exist. - /// The directory is not empty. - /// Function loads every file and attribute. Alls read-only flags will be removed before removing. - public static void DeleteDirectory( string uncDirectoryPath, bool recursive = false ) - { - Contract.Requires( !String.IsNullOrEmpty( uncDirectoryPath ) ); - - // Contents - if( recursive ) - { - foreach( Win32FileSystemEntry systemEntry in new Win32FileHandleCollection( QuickIOPath.Combine( uncDirectoryPath, QuickIOPatterns.PathMatchAll ) ) ) - { - // Create hit for current search result - var resultPath = QuickIOPath.Combine( uncDirectoryPath, systemEntry.Name ); - if( systemEntry.IsFile ) - { - DeleteFile( resultPath ); - } - - else if(/*is directory here*/ recursive ) - { - DeleteDirectory( resultPath, recursive ); - } - } - } - - // Remove specified - if( !Win32SafeNativeMethods.RemoveDirectory( uncDirectoryPath ) ) - { - int errorCode = Marshal.GetLastWin32Error(); - Win32ErrorCodes.NativeExceptionMapping( uncDirectoryPath, errorCode ); - } - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.Directory.Statistics.cs b/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.Directory.Statistics.cs deleted file mode 100644 index 3cf7cd4..0000000 --- a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.Directory.Statistics.cs +++ /dev/null @@ -1,95 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.Runtime.InteropServices; -using System.Security.Permissions; -using System.IO; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO.Engine -{ - /// - /// Provides internal methods. PathMatchAll IO operations are called from here. - /// - [FileIOPermission(SecurityAction.Demand, AllFiles = FileIOPermissionAccess.AllAccess, AllLocalFiles = FileIOPermissionAccess.AllAccess)] - internal static partial class QuickIOEngine - { - /// - /// Determines the statistics of the given directory. This includes the number of files, folders and the total size in bytes. - /// - /// PathInfo of the directory to generate the statistics. - /// Options - /// Provides the statistics of the directory - /// This error is fired if the specified path or a part of them does not exist. - public static QuickIOFolderStatisticResult GetDirectoryStatistics(QuickIOPathInfo pathInfo, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) - { - throw new NotImplementedException(); - } - - /// - /// Determines metadata of network shares - /// - /// Share to check - /// - public static QuickIODiskInformation GetDiskInformation(String rootPath) - { - Contract.Requires(!String.IsNullOrWhiteSpace(rootPath)); - Contract.Ensures(Contract.Result() != null); - - UInt64 freeBytes; - UInt64 totalBytes; - UInt64 totalFreeBytes; - - /* PInvoke request */ - if(!Win32SafeNativeMethods.GetDiskFreeSpaceEx(rootPath, out freeBytes, out totalBytes, out totalFreeBytes)) - { - Win32ErrorCodes.NativeExceptionMapping(rootPath, Marshal.GetLastWin32Error()); - } - - return new QuickIODiskInformation(freeBytes, totalBytes, totalFreeBytes); - } - - /// - /// Moves a file - /// - /// Full source path - /// Full target path - public static void MoveFile(string sourceFileName, string destFileName) - { - Contract.Requires(!String.IsNullOrWhiteSpace(sourceFileName)); - Contract.Requires(!String.IsNullOrWhiteSpace(destFileName)); - - if(!Win32SafeNativeMethods.MoveFile(sourceFileName, destFileName)) - { - Win32ErrorCodes.NativeExceptionMapping(sourceFileName, Marshal.GetLastWin32Error()); - } - } - - - #region Internal Directory - public static bool FileExists(string path) - { - Contract.Requires(!String.IsNullOrWhiteSpace(path)); - - int win32Error; - var attrs = QuickIOEngine.SafeGetAttributes(path, out win32Error); - - if(Equals(attrs, 0xffffffff)) - { - return false; - } - - if(!((FileAttributes)attrs).Contains(FileAttributes.Directory)) - { - return true; - } - - throw new UnmatchedFileSystemEntryTypeException(QuickIOFileSystemEntryType.File, QuickIOFileSystemEntryType.Directory, path); - } - #endregion - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.FileHandle.cs b/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.FileHandle.cs deleted file mode 100644 index 0f3736a..0000000 --- a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.FileHandle.cs +++ /dev/null @@ -1,82 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.IO; -using Microsoft.Win32.SafeHandles; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO.Engine -{ - internal static partial class QuickIOEngine - { - - /// - /// Returns the and fills from the passes path. - /// - /// Path to the file system entry - /// - /// This error is fired if the specified path or a part of them does not exist. - internal static SafeFileHandle CreateSafeFileHandle( QuickIOPathInfo pathInfo ) - { - Contract.Requires( pathInfo != null ); - - Contract.Ensures( Contract.Result() != null ); - - return CreateSafeFileHandle( pathInfo.FullNameUnc ); - } - - /// - /// Returns the and fills from the passes path. - /// - /// Path to the file system entry - /// - /// This error is fired if the specified path or a part of them does not exist. - private static SafeFileHandle CreateSafeFileHandle( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - Contract.Ensures( Contract.Result() != null ); - - return Win32SafeNativeMethods.CreateFile( path, FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero ); - } - - /// - /// Returns the and fills from the passes path. - /// - /// Path to the file system entry - /// - /// This error is fired if the specified path or a part of them does not exist. - internal static SafeFileHandle OpenReadWriteFileSystemEntryHandle( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - Contract.Ensures( Contract.Result() != null ); - - return Win32SafeNativeMethods.OpenReadWriteFileSystemEntryHandle( path, ( 0x40000000 | 0x80000000 ), FileShare.Read | FileShare.Write | FileShare.Delete, IntPtr.Zero, FileMode.Open, ( 0x02000000 ), IntPtr.Zero ); - } - - ///// - ///// Handles the options to the fired exception - ///// - //private static bool EnumerationHandleInvalidFileHandle( string path, QuickIOEnumerateOptions enumerateOptions, int win32Error ) - //{ - // Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - // try - // { - // QuickIOEngine.NativeExceptionMapping( path, win32Error ); - // } - // catch( Exception ) when (enumerateOptions.HasFlag( QuickIOEnumerateOptions.SuppressAllExceptions )) - // { - // return true; - // } - - - // return false; - //} - } -} diff --git a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.FileTimes.cs b/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.FileTimes.cs deleted file mode 100644 index 6dca5d6..0000000 --- a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.FileTimes.cs +++ /dev/null @@ -1,99 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO.Engine -{ - - internal static partial class QuickIOEngine - { - /// - /// Sets the dates and times of given directory or file. - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - public static void SetAllFileTimes( string pathUnc, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) - { - long longCreateTime = creationTimeUtc.ToFileTime(); - long longAccessTime = lastAccessTimeUtc.ToFileTime(); - long longWriteTime = lastWriteTimeUtc.ToFileTime(); - - using( SafeFileHandle fileHandle = OpenReadWriteFileSystemEntryHandle(pathUnc) ) - { - if( Win32SafeNativeMethods.SetAllFileTimes( fileHandle, ref longCreateTime, ref longAccessTime, ref longWriteTime ) == 0 ) - { - int win32Error = Marshal.GetLastWin32Error(); - Win32ErrorCodes.NativeExceptionMapping(pathUnc, win32Error ); - } - } - } - - /// - /// Sets the time at which the file or directory was created (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - public static void SetCreationTimeUtc( string pathUnc, DateTime utcTime ) - { - long longTime = utcTime.ToFileTime(); - using( SafeFileHandle fileHandle = OpenReadWriteFileSystemEntryHandle(pathUnc) ) - { - if( !Win32SafeNativeMethods.SetCreationFileTime( fileHandle, ref longTime, IntPtr.Zero, IntPtr.Zero ) ) - { - int win32Error = Marshal.GetLastWin32Error(); - Win32ErrorCodes.NativeExceptionMapping(pathUnc, win32Error ); - } - } - } - - /// - /// Sets the time at which the file or directory was last written to (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - public static void SetLastWriteTimeUtc( string pathUnc, DateTime utcTime ) - { - Contract.Requires(pathUnc != null ); - - long longTime = utcTime.ToFileTime(); - using( SafeFileHandle fileHandle = OpenReadWriteFileSystemEntryHandle(pathUnc) ) - { - if( !Win32SafeNativeMethods.SetLastWriteFileTime( fileHandle, IntPtr.Zero, IntPtr.Zero, ref longTime ) ) - { - int win32Error = Marshal.GetLastWin32Error(); - Win32ErrorCodes.NativeExceptionMapping(pathUnc, win32Error ); - } - } - } - - /// - /// Sets the time at which the file or directory was last accessed to (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - public static void SetLastAccessTimeUtc( string pathUnc, DateTime utcTime ) - { - Contract.Requires(pathUnc != null ); - - long longTime = utcTime.ToFileTime(); - using( SafeFileHandle fileHandle = OpenReadWriteFileSystemEntryHandle(pathUnc) ) - { - if( !Win32SafeNativeMethods.SetLastAccessFileTime( fileHandle, IntPtr.Zero, ref longTime, IntPtr.Zero ) ) - { - int win32Error = Marshal.GetLastWin32Error(); - Win32ErrorCodes.NativeExceptionMapping(pathUnc, win32Error ); - } - } - } - - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.Files.cs b/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.Files.cs deleted file mode 100644 index 3826c66..0000000 --- a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.Files.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.IO; -using System.Runtime.InteropServices; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO.Engine -{ - internal static partial class QuickIOEngine - { - /// - /// Creates a new file. - /// - /// The specified path already exists. - /// This error is fired if the specified path or a part of them does not exist. - public static void CreateFile( String path, FileAccess fileAccess = FileAccess.Write, FileShare fileShare = FileShare.None, FileMode fileMode = FileMode.Create, FileAttributes fileAttributes = 0 ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - using( var fileHandle = Win32SafeNativeMethods.CreateFile( path, fileAccess, fileShare, IntPtr.Zero, fileMode, fileAttributes, IntPtr.Zero ) ) - { - var win32Error = Marshal.GetLastWin32Error(); - if( fileHandle.IsInvalid ) - { - Win32ErrorCodes.NativeExceptionMapping( path, win32Error ); - } - } - } - - /// - /// Removes a file. - /// - /// Path to the file to remove - /// This error is fired if the specified file to remove does not exist. - public static void DeleteFile( String path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - // Remove all attributes - RemoveAllFileAttributes( path ); - - if( !Win32SafeNativeMethods.DeleteFile( path ) ) - { - Win32ErrorCodes.NativeExceptionMapping( path, Marshal.GetLastWin32Error() ); - } - } - - - /// - /// Deletes all files in the given directory. - /// - /// Path of directory to clear - /// If true all files in all all subfolders included - /// This error is fired if the specified path or a part of them does not exist. - /// This error will be fired when attempting a file to delete, which does not exist. - public static void DeleteFiles( String directoryPath, bool recursive = false ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( directoryPath ) ); - - IEnumerable allFilePaths = InternalEnumerateFileSystem.EnumerateSystemPaths( directoryPath, QuickIOPatterns.PathMatchAll, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions.None ); - foreach( var filePath in allFilePaths ) - { - DeleteFile( filePath ); - } - } - - /// - /// Copies a file and overwrite existing files if desired. - /// - /// Full source path - /// Full target path - /// Last error occured - /// true to overwrite existing files - /// True if copy succeeded, false if not. Check last Win32 Error to get further information. - /// This error is fired if the specified path or a part of them does not exist. - public static bool CopyFile( string sourceFilePath, string targetFilePath, out Int32 win32Error, bool overwrite = false ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( sourceFilePath ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( targetFilePath ) ); - - if( !Win32SafeNativeMethods.CopyFile( sourceFilePath, targetFilePath, !overwrite ) ) - { - win32Error = Marshal.GetLastWin32Error(); - return false; - } - - win32Error = 0; - return true; - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.FilesAttributes.cs b/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.FilesAttributes.cs deleted file mode 100644 index 6eb26e3..0000000 --- a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.FilesAttributes.cs +++ /dev/null @@ -1,133 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.ComponentModel; -using System.Diagnostics.Contracts; -using System.IO; -using System.Runtime.InteropServices; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO.Engine -{ - internal static partial class QuickIOEngine - { - /// - /// Adds a file attribute - /// - /// Affected target - /// Attribute to add - /// Attributes after add - /// true if added. false if already exists in attributes - public static bool TryAddAttribute( string path, FileAttributes attribute , out FileAttributes updatedAttributes) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - // read uncached attributes - updatedAttributes = GetAttributes( path ); - - if( /* contains */ (updatedAttributes & attribute ) != attribute ) - { - // is not present but will be set now - - updatedAttributes |= attribute; - SetAttributes( path, updatedAttributes); - - return true; - } - - return false; - } - - /// - /// Sets all attributes to - /// - /// Path to file or directory - /// This error will be fired if the specified path or a part of them does not exist. - public static FileAttributes RemoveAllFileAttributes( String path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - return SetAttributes( path, FileAttributes.Normal ); - } - - /// - /// Remove a file attribute - /// - /// Affected target - /// Attribute to remove - /// Attributes after remove - /// true if removed. false if not exists in attributes - public static bool TryRemoveAttribute( String path, FileAttributes attribute, out FileAttributes updatedAttributes ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - updatedAttributes = GetAttributes( path ); - - if(/* contains */ (updatedAttributes & attribute ) == attribute ) - { - // it is presen - updatedAttributes &= ~attribute; - SetAttributes( path, updatedAttributes); - - return true; - } - - return false; - } - - /// - /// Gets the of the file on the entry. - /// - /// The path to the entry. - /// The of the file on the entry. - /// This error is fired if the specified path or a part of them does not exist. - internal static FileAttributes GetAttributes( String uncPath ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( uncPath ) ); - - int win32Error; - var attrs = SafeGetAttributes( uncPath, out win32Error ); - Win32ErrorCodes.NativeExceptionMapping( uncPath, win32Error ); - - return ( FileAttributes )attrs; - } - - /// - /// Gets the of the file on the entry. - /// - /// The path to the entry. - /// Win32 Error Code - /// The of the file on the entry. - /// This error is fired if the specified path or a part of them does not exist. - internal static uint SafeGetAttributes( String path, out Int32 win32Error ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - uint attributes = Win32SafeNativeMethods.GetFileAttributes( path ); - win32Error = ( attributes ) == 0xffffffff ? Marshal.GetLastWin32Error() : 0; - return attributes; - } - - /// - /// Sets the specified of the entry on the specified path. - /// - /// The path to the entry. - /// A bitwise combination of the enumeration values. - /// Unmatched Exception - /// This error is fired if the specified path or a part of them does not exist. - public static FileAttributes SetAttributes( String path, FileAttributes attributes ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - if( !Win32SafeNativeMethods.SetFileAttributes( path, ( uint )attributes ) ) - { - var win32Error = Marshal.GetLastWin32Error(); - Win32ErrorCodes.NativeExceptionMapping( path, win32Error ); - } - - return attributes; - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.FindData.cs b/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.FindData.cs deleted file mode 100644 index fd55ca7..0000000 --- a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.FindData.cs +++ /dev/null @@ -1,155 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.IO; -using System.Runtime.InteropServices; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO.Engine -{ - internal static partial class QuickIOEngine - { - - - /// - /// Gets the from the passed path. - /// - /// Path - /// . Will be null if path does not exist. - /// true if path is valid and is set - /// - /// - /// QuickIOCommon.NativeExceptionMapping - /// if invalid handle found. - /// - /// This error is fired if the specified path or a part of them does not exist. - public static bool TryGetFindDataFromPath(string fullpath, out Win32FindData win32FindData) - { - Contract.Requires(!String.IsNullOrWhiteSpace(fullpath)); - - win32FindData = GetFindDataFromPath(fullpath); - return (win32FindData != null); - } - - - /// - /// Returns the and fills from the passes path. - /// - /// Path to the file system entry - /// - /// Last error code. 0 if no error occurs - /// - /// This error is fired if the specified path or a part of them does not exist. - private static Win32FileHandle FindFirstSafeFileHandle(string path, Win32FindData win32FindData, out Int32 win32Error) - { - Contract.Requires(!String.IsNullOrWhiteSpace(path)); - - Contract.Ensures(Contract.Result() != null); - - var result = Win32SafeNativeMethods.FindFirstFile(path, win32FindData); - win32Error = Marshal.GetLastWin32Error(); - - return result; - } - - /// - /// Reurns true if passed path exists - /// - /// Path to check - public static Boolean Exists(String path) - { - Contract.Requires(!String.IsNullOrWhiteSpace(path)); - - uint attributes = Win32SafeNativeMethods.GetFileAttributes(path); - return !Equals(attributes, 0xffffffff); - } - - ///// - ///// Returns the from specified - ///// - ///// Path to the file system entry - ///// - ///// This error is fired if the specified path or a part of them does not exist. - /// - /// - /// Returns the from specified - /// - /// Path to the file system entry - /// - public static Win32FindData SafeGetFindDataFromPath(string fullpath) - { - Contract.Requires(!String.IsNullOrWhiteSpace(fullpath)); - - Win32FindData win32FindData = new Win32FindData(); - int win32Error; - using(Win32FileHandle fileHandle = FindFirstSafeFileHandle(fullpath, win32FindData, out win32Error)) - { - // Take care of invalid handles - if(fileHandle.IsInvalid) - { - Win32ErrorCodes.NativeExceptionMapping(fullpath, win32Error); - } - - // Treffer auswerten - // Ignore . and .. directories - if(!win32FindData.IsSystemDirectoryEntry()) - { - return win32FindData; - } - } - - return null; - } - - public static Win32FindData GetFindDataFromPath(string fullpath, QuickIOFileSystemEntryType? estimatedFileSystemEntryType = null) - { - Contract.Requires(fullpath != null); - //Changed to allow paths which do not exist: - //Contract.Ensures( Contract.Result() != null ); - if(!QuickIOPath.Exists(fullpath)) - { - return null; - } - Win32FindData win32FindData = SafeGetFindDataFromPath(fullpath); - - if(win32FindData == null) - { - //Changed to allow paths which do not exist: - //throw new PathNotFoundException( fullpath ); - return null; - } - - // Check for correct type - switch(estimatedFileSystemEntryType) - { - case QuickIOFileSystemEntryType.Directory: - { - // Check for directory flag - if(win32FindData.dwFileAttributes.Contains(FileAttributes.Directory)) - { - return win32FindData; - } - throw new UnmatchedFileSystemEntryTypeException(QuickIOFileSystemEntryType.Directory, QuickIOFileSystemEntryType.File, fullpath); - } - case QuickIOFileSystemEntryType.File: - { - // Check for directory flag - if(!win32FindData.dwFileAttributes.Contains(FileAttributes.Directory)) - { - return win32FindData; - } - throw new UnmatchedFileSystemEntryTypeException(QuickIOFileSystemEntryType.File, QuickIOFileSystemEntryType.Directory, fullpath); - } - case null: - default: - { - return win32FindData; - } - } - } - } -} diff --git a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.Shares.cs b/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.Shares.cs deleted file mode 100644 index d8bcadb..0000000 --- a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.Shares.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Runtime.InteropServices; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO.Engine -{ - internal static partial class QuickIOEngine - { - /// - /// Enumerate shares of specific machine. If no machine is specified, local machine is used - /// - /// Collection of - public static IEnumerable EnumerateShares( QuickIOShareApiReadLevel level, String machineName = null ) where T : IWin32ApiShareInfo - { - Contract.Ensures( Contract.Result>() != null ); - - // Specify - string machine = String.IsNullOrEmpty( machineName ) ? Environment.MachineName : machineName; - IntPtr buffer = IntPtr.Zero; - - try - { - int resumeHandle = 0; - int entriesRead, totalEntries; - int returnCode = Win32SafeNativeMethods.NetShareEnum( machineName, ( int )level, out buffer, -1, out entriesRead, out totalEntries, ref resumeHandle ); - - // Available return codes: http://msdn.microsoft.com/en-us/library/windows/desktop/bb525387(v=vs.85).aspx - - //if( returnCode == Win32ErrorCodes.ERROR_ACCESS_DENIED ) // Access Denied - //{ - // level = QuickIOShareApiReadLevel.Normal - // // Admin required, but not granted? try with normal usr - // returnCode = QuickIOEngine.GetShareEnumResult( machine, level, ref buffer, ref entriesRead, ref totalEntries, ref resumeHandle ); - //} - - //// skip if zero or no entries - //if( returnCode != 0 || entriesRead <= 0 ) // we only handle return 0 here - //{ - // yield break; - //} - - if( returnCode > 0 ) - { - Type type = typeof( T ); - int typeSize = Marshal.SizeOf( type ); - - for( int i = 0, currentDataItem = buffer.ToInt32() ;i < entriesRead ;i++, currentDataItem += typeSize ) - { - IWin32ApiShareInfo shareInfo = ( T )Marshal.PtrToStructure( new IntPtr( currentDataItem ), typeof( T ) ); - yield return new QuickIOShareInfo( machine, shareInfo.GetShareName(), shareInfo.GetShareType(), shareInfo.GetRemark() ); - } - } - } - finally - { - // Clean up buffer allocated by system - // TODO: check if this is enough here - if( buffer != IntPtr.Zero ) - { - Win32SafeNativeMethods.NetApiBufferFree( buffer ); - } - } - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.cs b/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.cs deleted file mode 100644 index 26aeb93..0000000 --- a/src/SchwabenCode.QuickIO/Engine/QuickIOEngine.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.IO; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO.Engine -{ - /// - /// Provides several methods for internal purposes. - /// - internal static partial class QuickIOEngine - { - /// - /// Common Constants - /// - public static class Constants - { - /// - /// Represents return value of invalid request of get the file attributes of a system entry. - /// Is equal to UInt32.MaxValue - /// See http://msdn.microsoft.com/en-us/library/windows/desktop/aa364944(v=vs.85).aspx - /// - public const UInt32 InvalidFileAttributes = 0xffffffff; - } - - /// - /// Determines the type based on the attributes of the path - /// - /// Full path - /// - internal static QuickIOFileSystemEntryType DetermineFileSystemEntry(string fullPath) - { - Contract.Requires(!String.IsNullOrWhiteSpace(fullPath)); - - Win32FindData findData = Engine.QuickIOEngine.GetFindDataFromPath(fullPath); - - return !findData.dwFileAttributes.Contains(FileAttributes.Directory) ? QuickIOFileSystemEntryType.File : QuickIOFileSystemEntryType.Directory; - } - - /// - /// Determines the type based on the attributes of the handle - /// - /// - /// - internal static QuickIOFileSystemEntryType DetermineFileSystemEntry(Win32FindData findData) - { - Contract.Requires(findData != null); - - return !findData.dwFileAttributes.Contains(FileAttributes.Directory) ? QuickIOFileSystemEntryType.File : QuickIOFileSystemEntryType.Directory; - } - } -} diff --git a/src/SchwabenCode.QuickIO/Engine/README.md b/src/SchwabenCode.QuickIO/Engine/README.md deleted file mode 100644 index 6f7fd37..0000000 --- a/src/SchwabenCode.QuickIO/Engine/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## README for Internal Classes - -### Rules -- Internal classes only accepting strings. No complex QuickIO specific types. \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/FileAttributesExtensions.cs b/src/SchwabenCode.QuickIO/FileAttributesExtensions.cs deleted file mode 100644 index a88ba18..0000000 --- a/src/SchwabenCode.QuickIO/FileAttributesExtensions.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using System.IO; - -namespace SchwabenCode.QuickIO -{ - public static class FileAttributesExtensions - { - - /// - /// Removes a to the existing collection . - /// - /// collection - /// Attribute to remove - /// - public static FileAttributes Remove(this FileAttributes source, FileAttributes attrToRemove) - { - FileAttributes updated = source &= ~attrToRemove; - - return updated; - } - - /// - /// Checks whether the given attribute in the collection is included. - /// - /// collection - /// Attribute to check - /// True if exists, false if not - public static bool Contains(this FileAttributes source, FileAttributes attr) - { - return (source & attr) != 0; - } - - /// - /// Adds another to the existing collection - /// - /// collection - /// Attribute to add or remove - /// true to add, false to remove - /// - public static FileAttributes Force(this FileAttributes source, FileAttributes attr, bool existance) - { - return existance ? Add(source, attr) : Remove(source, attr); - } - - /// - /// Adds a to the existing collection . - /// - /// collection - /// Attribute to add - /// - public static FileAttributes Add(this FileAttributes source, FileAttributes attrToAdd) - { - source |= attrToAdd; - return source; - } - } -} diff --git a/src/SchwabenCode.QuickIO/Properties/AssemblyInfo.cs b/src/SchwabenCode.QuickIO/Properties/AssemblyInfo.cs deleted file mode 100644 index 35909d1..0000000 --- a/src/SchwabenCode.QuickIO/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("SchwabenCode.QuickIO")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("SchwabenCode.QuickIO")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("b33dbcee-42f4-4570-b4ef-5412ce4a4bda")] - -// Expose to test -[assembly: InternalsVisibleTo("SchwabenCode.QuickIO.UnitTests")] -[assembly: InternalsVisibleTo("SchwabenCode.QuickIO.IntegrationTests")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] - -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/SchwabenCode.QuickIO/QuickIO.cs b/src/SchwabenCode.QuickIO/QuickIO.cs deleted file mode 100644 index 8cc697b..0000000 --- a/src/SchwabenCode.QuickIO/QuickIO.cs +++ /dev/null @@ -1,253 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.IO; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - /// - /// QuickIO provides you methods to interact with the file system - local and remote targets - /// - public class QuickIO - { - /// - /// Gets the of the directory or file. - /// - /// The path to the directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes(string path, FileAttributes attributes) - { - Contract.Requires(!String.IsNullOrWhiteSpace(path)); - QuickIOEngine.SetAttributes(QuickIOPath.ToPathUnc(path), attributes); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes(QuickIOPathInfo info, FileAttributes attributes) - { - Contract.Requires(info != null); - SetAttributes(info.FullNameUnc, attributes); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes(QuickIOFileInfo info, FileAttributes attributes) - { - Contract.Requires(info != null); - SetAttributes(info.PathInfo, attributes); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes(QuickIODirectoryInfo info, FileAttributes attributes) - { - Contract.Requires(info != null); - SetAttributes(info.PathInfo, attributes); - } - - #region Attributes - /// - /// Gets the of the directory or file. - /// - /// The path to the directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes(string path) - { - Contract.Requires(!String.IsNullOrWhiteSpace(path)); - return QuickIOEngine.GetAttributes(QuickIOPath.ToPathUnc(path)); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes(QuickIOPathInfo info) - { - Contract.Requires(info != null); - return GetAttributes(info.FullNameUnc); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes(QuickIOFileInfo info) - { - Contract.Requires(info != null); - return GetAttributes(info.PathInfo); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes(QuickIODirectoryInfo info) - { - Contract.Requires(info != null); - return GetAttributes(info.PathInfo); - } - - #endregion - - #region Remove Attribute - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute(string path, FileAttributes attribute) - { - Contract.Requires(!String.IsNullOrWhiteSpace(path)); - - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(QuickIOPath.ToPathUnc(path), attribute, out updatedAttributes); - - return result; - } - - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute(QuickIOPathInfo info, FileAttributes attribute) - { - Contract.Requires(info != null); - - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute(QuickIOFileInfo info, FileAttributes attribute) - { - Contract.Requires(info != null); - - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute(QuickIODirectoryInfo info, FileAttributes attribute) - { - Contract.Requires(info != null); - - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - #endregion - - #region Add Attribute - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute(string path, FileAttributes attribute) - { - Contract.Requires(!String.IsNullOrWhiteSpace(path)); - - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(QuickIOPath.ToPathUnc(path), attribute, out updatedAttributes); - - return result; - } - - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute(QuickIOPathInfo info, FileAttributes attribute) - { - Contract.Requires(info != null); - - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute(QuickIOFileInfo info, FileAttributes attribute) - { - Contract.Requires(info != null); - - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute(QuickIODirectoryInfo info, FileAttributes attribute) - { - Contract.Requires(info != null); - - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - #endregion Add Attribute - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectory.Compress.cs b/src/SchwabenCode.QuickIO/QuickIODirectory.Compress.cs deleted file mode 100644 index fda3cb7..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectory.Compress.cs +++ /dev/null @@ -1,67 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System.IO; -using System; -using System.IO.Compression; -using System.Diagnostics.Contracts; - -#if NET45_OR_GREATER - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIODirectory - { - /// - /// Compresses a directory by using - /// ZipFile.CreateFromDirectory - /// - /// - /// Directory fullname to zip - /// Zipfile fullname to save - /// true to overwrite existing zipfile - /// - /// True to include basedirectory - /// if does not exist. - /// if does exist and is false. - public static void Compress( String directoryFullPath, String zipFullPath, bool overWriteExistingZip = false, CompressionLevel compressionLevel = CompressionLevel.Fastest, bool includeBaseDirectory = false ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( directoryFullPath ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( zipFullPath ) ); - - if( !QuickIODirectory.Exists( directoryFullPath ) ) - { - throw new DirectoryNotFoundException( $"Directory to zip '{directoryFullPath}' does not exist." ); - } - - if( !overWriteExistingZip && ( QuickIOFile.Exists( zipFullPath ) ) ) - { - throw new FileAlreadyExistsException( $"The target zipFile name '{zipFullPath}' already exists." ); - } - - throw new NotImplementedException(); - //ZipFile.CreateFromDirectory( directoryFullPath, zipFullPath, compressionLevel, includeBaseDirectory ); - } - - /// - /// Compresses a directory by using - /// ZipFile.CreateFromDirectory - /// - /// - /// Directory to zip - /// Zipfile fullname to save - /// true to overwrite existing zipfile - /// - /// True to include basedirectory - public static void Compress( QuickIODirectoryInfo directory, String zipFullPath, bool overWriteExistingZip = false, CompressionLevel compressionLevel = CompressionLevel.Fastest, bool includeBaseDirectory = false ) - { - Contract.Requires( directory != null ); - Contract.Requires( !String.IsNullOrWhiteSpace( zipFullPath ) ); - - Compress( directory.FullName, zipFullPath, overWriteExistingZip, compressionLevel, includeBaseDirectory ); - } - } -} -#endif \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/QuickIODirectory.Copy.cs b/src/SchwabenCode.QuickIO/QuickIODirectory.Copy.cs deleted file mode 100644 index d394c39..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectory.Copy.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.Threading; -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIODirectory - { - /// - /// Copies a directory and all contents - /// - /// Source directory - /// Target directory - /// true to overwrite existing files - /// Cancallation Token - public static void Copy( String source, String target, bool overwrite = false, CancellationToken cancellationToken = default( CancellationToken ) ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( source ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( target ) ); - - Copy( new QuickIODirectoryInfo( source ), new QuickIOPathInfo( target ), overwrite, cancellationToken ); - } - - /// - /// Copies a directory and all contents - /// - /// Source directory - /// Target directory - /// true to overwrite existing files - /// Cancallation Token - public static void Copy( QuickIODirectoryInfo source, QuickIOPathInfo target, bool overwrite = false, CancellationToken cancellationToken = default( CancellationToken ) ) - { - Contract.Requires( source != null ); - Contract.Requires( target != null ); - - throw new NotImplementedException(); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectory.Create.cs b/src/SchwabenCode.QuickIO/QuickIODirectory.Create.cs deleted file mode 100644 index 44c6771..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectory.Create.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System.Diagnostics.Contracts; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIODirectory - { - /// - /// Creates a new directory. If is false, the parent directory must exist. - /// - /// The path to the directory. - /// If is false, the parent directory must exist. - /// http://msdn.microsoft.com/en-us/library/54a0at6s(v=vs.110).aspx - /// The specified path already exists. - /// One or more intermediate directories do not exist; this function will only create the final directory in the path. - /// - /// Creates directory structure - /// - /// public static void Create_With_StringPath_Example() - /// { - /// // Creates directory C:\temp\QuickIOTest\sub\folder\tree and all not existing parent folders - /// QuickIODirectory.Create( @"C:\temp\QuickIOTest\sub\folder\tree", recursive: true ); - /// } - /// - /// - /// - /// Shows how to handle sample exception if parent directory does not exist. - /// - /// public static void Create_With_StringPath_Example() - /// { - /// try - /// { - /// QuickIODirectory.Create( @"C:\temp\QuickIOTest\sub\folder\tree", recursive: false ); - /// } - /// catch ( PathNotFoundException pathNotFoundException ) - /// { - /// // Parent directory does not exist. - /// } - /// } - /// - /// - public static void Create(string path, bool recursive = false) - { - Contract.Requires( !string.IsNullOrWhiteSpace( path ) ); - Create( new QuickIOPathInfo( path ), recursive ); - } - - /// - /// Creates a new directory. If is false, the parent directory must exist. - /// - /// The directory. - /// If is false, the parent directory must exist. - /// http://msdn.microsoft.com/en-us/library/54a0at6s(v=vs.110).aspx - /// The specified path already exists. - /// One or more intermediate directories do not exist; this function will only create the final directory in the path. - /// - /// Creates directory structure - /// - /// public static void Create_With_PathInfo_Example( ); - /// { - /// QuickIOPathInfo pathInfo = new QuickIOPathInfo( @"C:\temp\QuickIOTest\sub\folder\tree" ); - /// - /// // Creates directory C:\temp\QuickIOTest\sub\folder\tree and all not existing parent folders - /// QuickIODirectory.Create( pathInfo, recursive: true ); - /// } - /// - /// - /// - /// Shows how to handle sample exception if parent directory does not exist. - /// - /// public static void Create_With_StringPath_Example() - /// { - /// QuickIOPathInfo pathInfo = new QuickIOPathInfo( @"C:\temp\QuickIOTest\sub\folder\tree" ); - /// - /// try - /// { - /// QuickIODirectory.Create( pathInfo, recursive: false ); - /// } - /// catch ( PathNotFoundException pathNotFoundException ) - /// { - /// // Parent directory does not exist. - /// } - /// } - /// - /// - public static void Create( QuickIOPathInfo path, bool recursive = false ) - { - Contract.Requires( path != null ); - QuickIOEngine.CreateDirectory( path.FullNameUnc, recursive ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectory.Delete.cs b/src/SchwabenCode.QuickIO/QuickIODirectory.Delete.cs deleted file mode 100644 index a4c6ae3..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectory.Delete.cs +++ /dev/null @@ -1,95 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - - -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIODirectory - { - /// - /// Deletes the specified directory and, if indicated, any subdirectories and files in the directory. - /// - /// The name of the directory to remove. - /// true to remove directories, subdirectories, and files in path; otherwise, false. - /// http://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx - /// One or more intermediate directories do not exist; this function will only create the final directory in the path. - /// The directory is not empty. - /// - /// Creates directory structure - /// - /// public static void Create_With_StringPath_Example() - /// { - /// // Deletes directory C:\temp\QuickIOTest\sub\folder\tree and subfolders and files - /// QuickIODirectory.Delete( @"C:\temp\QuickIOTest\sub\folder\tree", recursive: true ); - /// } - /// - /// - /// - /// Shows how to handle sample exception if directory is not empty - /// - /// public static void Create_With_StringPath_Example() - /// { - /// try - /// { - /// QuickIODirectory.Delete( @"C:\temp\QuickIOTest\sub\folder\tree", recursive: false ); - /// } - /// catch ( DirectoryNotEmptyException directoryNotEmptyException ) - /// { - /// // Directoy is not empty - /// } - /// } - /// - /// - public static void Delete( string path, bool recursive = false ) - { - Delete( new QuickIOPathInfo( path ), recursive ); - } - - /// - /// Deletes the specified directory and, if indicated, any subdirectories and files in the directory. - /// - /// The name of the directory to remove. - /// true to remove directories, subdirectories, and files in path; otherwise, false. - /// http://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx - /// One or more intermediate directories do not exist; this function will only create the final directory in the path. - /// The directory is not empty. - /// - /// Creates directory structure - /// - /// public static void Create_With_StringPath_Example() - /// { - /// QuickIOPathInfo pathInfo = new QuickIOPathInfo( @"C:\temp\QuickIOTest\sub\folder\tree" ); - /// - /// // Deletes directory C:\temp\QuickIOTest\sub\folder\tree and subfolders and files - /// QuickIODirectory.Delete( pathInfo, recursive: true ); - /// } - /// - /// - /// - /// Shows how to handle sample exception if directory is not empty - /// - /// public static void Create_With_StringPath_Example() - /// { - /// QuickIOPathInfo pathInfo = new QuickIOPathInfo( @"C:\temp\QuickIOTest\sub\folder\tree" ); - /// - /// try - /// { - /// QuickIODirectory.Delete( pathInfo, recursive: false ); - /// } - /// catch ( DirectoryNotEmptyException directoryNotEmptyException ) - /// { - /// // Directoy is not empty - /// } - /// } - /// - /// - public static void Delete( QuickIOPathInfo info, bool recursive = false ) - { - QuickIOEngine.DeleteDirectory( info.FullNameUnc, recursive ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectory.Enumerations.cs b/src/SchwabenCode.QuickIO/QuickIODirectory.Enumerations.cs deleted file mode 100644 index 5ad1e38..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectory.Enumerations.cs +++ /dev/null @@ -1,218 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.IO; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIODirectory - { - #region EnumerateDirectoryPaths - - /// - /// Returns an enumerable collection of directory names in a specified path. - /// - /// The directory to search. - /// Search pattern. Uses Win32 native filtering. - /// - /// Specifies the type of path to return. - /// Options - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. - /// http://msdn.microsoft.com/en-us/library/dd383304(v=vs.110).aspx - public static IEnumerable EnumerateDirectoryPaths( string path, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( pattern ) ); - - return InternalEnumerateFileSystem.EnumerateSystemPaths( path, pattern, searchOption, enumerateOptions, pathFormatReturn, QuickIOFileSystemEntryType.Directory ); - } - - /// - /// Returns an enumerable collection of directory names in a specified path. - /// - /// The directory to search. - /// Search pattern. Uses Win32 native filtering. - /// - /// Specifies the type of path to return. - /// Options - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. - /// http://msdn.microsoft.com/en-us/library/dd383304(v=vs.110).aspx - public static IEnumerable EnumerateDirectoryPaths( QuickIODirectoryInfo info, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( info != null ); - Contract.Requires( !String.IsNullOrWhiteSpace( pattern ) ); - - return EnumerateDirectoryPaths( info.FullNameUnc, pattern, searchOption, pathFormatReturn, enumerateOptions ); - } - #endregion - - #region EnumerateDirectories - /// - /// Returns an enumerable collection of directories in a specified path. - /// - /// The directory to search. - /// Search pattern. Uses Win32 native filtering. - /// - /// Options - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. - /// http://msdn.microsoft.com/en-us/library/dd383304(v=vs.110).aspx - /// - /// - /// // Get subfolders - /// IEnumerable>QuickIODirectoryInfo< allSubFolders = QuickIODirectory.EnumerateDirectories( @"C:\temp\QuickIO", SearchOption.AllDirectories ); - /// - /// foreach ( QuickIODirectoryInfo directoryInfo in allSubFolders ) - /// { - /// Console.WriteLine( "Directory found: {0} Readonly: {1}", directoryInfo.Path, directoryInfo.IsReadOnly ); - /// } - /// - /// - public static IEnumerable EnumerateDirectories( string path, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - return InternalEnumerateFileSystem.EnumerateDirectories( path, pattern, searchOption, enumerateOptions ); - } - - /// - /// Returns an enumerable collection of directories in a specified path. - /// - /// The directory to search. - /// Search pattern. Uses Win32 native filtering. - /// - /// Options - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. - /// http://msdn.microsoft.com/en-us/library/dd383304(v=vs.110).aspx - public static IEnumerable EnumerateDirectories( QuickIODirectoryInfo info, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - return EnumerateDirectories( info.FullNameUnc, pattern, searchOption, enumerateOptions ); - } - #endregion - - #region EnumerateFilePaths - /// - /// Returns an enumerable collection of file names in a specified path. - /// - /// The directory to search. - /// Search pattern. Uses Win32 native filtering. - /// - /// Specifies the type of path to return. - /// Options - /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. - /// http://msdn.microsoft.com/en-us/library/dd383458(v=vs.110).aspx - public static IEnumerable EnumerateFilePaths( string path, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - return InternalEnumerateFileSystem.EnumerateSystemPaths( path, pattern, searchOption, enumerateOptions, pathFormatReturn, QuickIOFileSystemEntryType.File ); - } - - /// - /// Returns an enumerable collection of file names in a specified path. - /// - /// The directory to search. - /// Search pattern. Uses Win32 native filtering. - /// - /// Specifies the type of path to return. - /// Options - /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. - /// http://msdn.microsoft.com/en-us/library/dd383458(v=vs.110).aspx - public static IEnumerable EnumerateFilePaths( QuickIODirectoryInfo info, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( info != null ); - Contract.Requires( !String.IsNullOrWhiteSpace( pattern ) ); - - return EnumerateFilePaths( info.FullNameUnc, pattern, searchOption, pathFormatReturn, enumerateOptions ); - } - - #endregion - - #region EnumerateFiles - - /// - /// Returns an enumerable collection of files in a specified path. - /// - /// The directory to search. - /// Search pattern. Uses Win32 native filtering. - /// - /// Options - /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. - /// http://msdn.microsoft.com/en-us/library/dd383458(v=vs.110).aspx - /// - /// - /// // Get subfiles - /// IEnumerable<QuickIOFileInfo> allSubFiles = QuickIODirectory.EnumerateFiles( @"C:\temp\QuickIO", SearchOption.AllDirectories ); - /// - /// foreach ( QuickIOFileInfo fileInfo in allSubFiles ) - /// { - /// Console.WriteLine( "File found: {0} Readonly: {1}", fileInfo.Path, fileInfo.IsReadOnly ); - /// } - /// - /// - public static IEnumerable EnumerateFiles( string path, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( pattern ) ); - - return InternalEnumerateFileSystem.EnumerateFiles( path, pattern, searchOption, enumerateOptions ); - } - - - /// - /// Returns an enumerable collection of files in a specified path. - /// - /// The directory to search. - /// Search pattern. Uses Win32 native filtering. - /// - /// Options - /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. - /// http://msdn.microsoft.com/en-us/library/dd383458(v=vs.110).aspx - public static IEnumerable EnumerateFiles(QuickIODirectoryInfo directoryInfo, - String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, - QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None) - { - Contract.Requires(directoryInfo != null); - Contract.Requires(!String.IsNullOrWhiteSpace(pattern)); - - return EnumerateFiles(directoryInfo.FullNameUnc, pattern, searchOption, enumerateOptions); - } - - #endregion - - /// - /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories. - /// - /// The directory to search. - /// Search pattern. Uses Win32 native filtering. - /// Options - /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. - /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. - /// http://msdn.microsoft.com/en-us/library/dd383459(v=vs.110).aspx - public static IEnumerable EnumerateFileSystemEntries( string path, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( pattern ) ); - - return InternalEnumerateFileSystem.EnumerateFileSystemEntries( path, pattern, searchOption, enumerateOptions ); - } - /// - /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories. - /// - /// The directory to search. - /// Search pattern. Uses Win32 native filtering. - /// Options - /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. - /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. - /// http://msdn.microsoft.com/en-us/library/dd383459(v=vs.110).aspx - public static IEnumerable EnumerateFileSystemEntries( QuickIODirectoryInfo directoryInfo, String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( directoryInfo != null ); - Contract.Requires( !String.IsNullOrWhiteSpace( pattern ) ); - - return EnumerateFileSystemEntries( directoryInfo.FullNameUnc, pattern, searchOption, enumerateOptions ); - } - - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectory.Exists.cs b/src/SchwabenCode.QuickIO/QuickIODirectory.Exists.cs deleted file mode 100644 index bb00291..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectory.Exists.cs +++ /dev/null @@ -1,74 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System.IO; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIODirectory - { - #region Exist - /// - /// Checks whether the given directory exists. - /// - /// The path to test. - /// true if exists; otherwise, false. - /// http://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx - /// Searched for file but found folder. - /// Path is invalid. - public static bool Exists(string path) - { - return InternalDirectoryExists(path); - } - - /// - /// Checks whether the given directory exists. - /// - /// The path to test. - /// true if exists; otherwise, false. - /// http://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx - /// Searched for file but found folder. - /// Path is invalid. - public static bool Exists(QuickIOPathInfo pathInfo) - { - return Exists(pathInfo.FullNameUnc); - } - - /// - /// Checks whether the given directory exists. - /// - /// The path to test. - /// true if exists; otherwise, false. - /// http://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx - /// Searched for file but found folder. - /// Path is invalid. - public static bool Exists(QuickIODirectoryInfo directoryInfo) - { - return Exists(directoryInfo.FullNameUnc); - } - - #endregion - - #region Internal Directory - private static bool InternalDirectoryExists(string uncPath) - { - int win32Error; - var attrs = QuickIOEngine.SafeGetAttributes(uncPath, out win32Error); - - if(Equals(attrs, 0xffffffff)) - { - return false; - } - if(((FileAttributes)attrs).Contains(FileAttributes.Directory)) - { - return true; - } - - throw new UnmatchedFileSystemEntryTypeException(QuickIOFileSystemEntryType.Directory, QuickIOFileSystemEntryType.File, uncPath); - } - #endregion - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectory.Metadata.cs b/src/SchwabenCode.QuickIO/QuickIODirectory.Metadata.cs deleted file mode 100644 index 54c929d..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectory.Metadata.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIODirectory - { - /// - /// Receives of current directory - /// - /// - public static QuickIODirectoryMetadata EnumerateDirectoryMetadata( String path, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( Contract.Result() != null ); - - return InternalEnumerateFileSystem.EnumerateDirectoryMetadata( path, enumerateOptions ); - } - - /// - /// Receives of current directory - /// - /// - public static QuickIODirectoryMetadata EnumerateDirectoryMetadata( QuickIODirectoryInfo directoryInfo, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( directoryInfo != null ); - Contract.Ensures( Contract.Result() != null ); - - return EnumerateDirectoryMetadata( directoryInfo.PathInfo, enumerateOptions ); - } - - /// - /// Receives of current directory - /// - /// - public static QuickIODirectoryMetadata EnumerateDirectoryMetadata( QuickIOPathInfo pathInfo, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( pathInfo != null ); - Contract.Ensures( Contract.Result() != null ); - - return EnumerateDirectoryMetadata( pathInfo.FullNameUnc, enumerateOptions ); - } - - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectory.Move.cs b/src/SchwabenCode.QuickIO/QuickIODirectory.Move.cs deleted file mode 100644 index 2783c62..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectory.Move.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Runtime.InteropServices; -using System.Diagnostics.Contracts; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIODirectory - { - /// - /// Moves a directory - /// - /// Fullname to move - /// Full targetname - /// true to overwrite target - /// Target exists - public static void Move( String from, String to, bool overwrite = false ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( from ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( to ) ); - - if( !overwrite && Exists( to ) ) - { - throw new DirectoryAlreadyExistsException( "Target directory already exists.", to ); - } - - if( !Win32SafeNativeMethods.MoveFile( from, to ) ) - { - int win32Error = Marshal.GetLastWin32Error(); - Win32ErrorCodes.NativeExceptionMapping( from, win32Error ); - } - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectory.Statistics.cs b/src/SchwabenCode.QuickIO/QuickIODirectory.Statistics.cs deleted file mode 100644 index 495d285..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectory.Statistics.cs +++ /dev/null @@ -1,103 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - /// - /// Provides static methods to access folders. For example creating, deleting and retrieving content and security information such as the owner. - /// - public static partial class QuickIODirectory - { - #region GetStatistics - - /// - /// Gets the directory statistics: total files, folders and bytes - /// - /// - /// A object that holds the folder statistics such as number of folders, files and total bytes - /// - /// This example shows how to call - /// GetStatistics - /// - /// and write the result to the console. - /// - /// public static void GetStatistics_With_StringPath_Example() - /// { - /// const string targetDirectoryPath = @"C:\temp\QuickIOTest"; - /// - /// // Get statistics - /// QuickIOFolderStatisticResult statsResult = QuickIODirectory.GetStatistics( targetDirectoryPath ); - /// - /// // Output - /// Console.WriteLine( "[Stats] Folders: '{0}' Files: '{1}' Total TotalBytes '{2}'", statsResult.FolderCount, statsResult.FileCount, statsResult.TotalBytes ); - /// } - /// - /// - public static QuickIOFolderStatisticResult GetStatistics( String path ) - { - return GetStatistics( new QuickIOPathInfo( path ) ); - } - - /// - /// Gets the directory statistics: total files, folders and bytes - /// - /// - /// A object that holds the folder statistics such as number of folders, files and total bytes - /// - /// This example shows how to call - /// GetStatistics - /// - /// with and write the result to the console. - /// - ///public static void GetStatistics_With_PathInfo_Example() - ///{ - /// QuickIOPathInfo targetDirectoryPathInfo = new QuickIOPathInfo( @"C:\temp\QuickIOTest" ); - /// - /// // Get statistics - /// QuickIOFolderStatisticResult stats = QuickIODirectory.GetStatistics( targetDirectoryPathInfo ); - /// - /// // Output - /// Console.WriteLine( "[Stats] Folders: '{0}' Files: '{1}' Total TotalBytes '{2}'", stats.FolderCount, stats.FileCount, stats.TotalBytes ); - ///} - /// - /// - public static QuickIOFolderStatisticResult GetStatistics( QuickIOPathInfo pathInfo ) - { - return QuickIOEngine.GetDirectoryStatistics( pathInfo ); - } - - /// - /// Gets the directory statistics: total files, folders and bytes - /// - /// - /// A object that holds the folder statistics such as number of folders, files and total bytes - /// - /// This example shows how to call - /// GetStatistics - /// - /// with and write the result to the console. - /// - ///public static void GetStatistics_With_DirectoryInfo_Example() - ///{ - /// QuickIODirectoryInfo targetDirectoryPathInfo = new QuickIODirectoryInfo( @"C:\temp\QuickIOTest" ); - /// - /// // Get statistics - /// QuickIOFolderStatisticResult stats = QuickIODirectory.GetStatistics( targetDirectoryPathInfo ); - /// - /// // Output - /// Console.WriteLine( "[Stats] Folders: '{0}' Files: '{1}' Total TotalBytes '{2}'", stats.FolderCount, stats.FileCount, stats.TotalBytes ); - ///} - /// - /// - public static QuickIOFolderStatisticResult GetStatistics( QuickIODirectoryInfo directoryInfo ) - { - return QuickIOEngine.GetDirectoryStatistics( directoryInfo.PathInfo ); - } - #endregion - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectoryInfo.Enumerations.cs b/src/SchwabenCode.QuickIO/QuickIODirectoryInfo.Enumerations.cs deleted file mode 100644 index 01ada28..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectoryInfo.Enumerations.cs +++ /dev/null @@ -1,125 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.IO; - - -namespace SchwabenCode.QuickIO -{ - public sealed partial class QuickIODirectoryInfo - { - #region EnumerateDirectoryPaths - - /// - /// Returns an enumerable collection of directory names. - /// - /// Search pattern. Uses Win32 native filtering. - /// Specifiy depth with - /// Type of return - /// Options - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. - public IEnumerable EnumerateDirectoryPaths( String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( pattern ) ); - Contract.Ensures( Contract.Result>() != null ); - - return QuickIODirectory.EnumerateDirectoryPaths( FullNameUnc, pattern, searchOption, pathFormatReturn, enumerateOptions ); - } - - #endregion - - #region EnumerateDirectories - - /// - /// Returns an enumerable collection of directories in a specified path. - /// - /// Search pattern. Uses Win32 native filtering. - /// Specifiy depth with - /// Options - /// An enumerable collection of the full names (including paths) for the directories in the directory specified by path. - public IEnumerable EnumerateDirectories( String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( pattern ) ); - Contract.Ensures( Contract.Result>() != null ); - - return QuickIODirectory.EnumerateDirectories( FullNameUnc, pattern, searchOption, enumerateOptions ); - } - #endregion - - #region EnumerateFilePaths - - /// - /// Returns an enumerable collection of file names in a specified path. - /// - /// Search pattern. Uses Win32 native filtering. - /// Specifiy depth with - /// Specifies the type of path to return. - /// Options - /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. - public IEnumerable EnumerateFilePaths( String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOPathType pathFormatReturn = QuickIOPathType.Regular, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( pattern ) ); - Contract.Ensures( Contract.Result>() != null ); - - return QuickIODirectory.EnumerateFilePaths( FullNameUnc, pattern, searchOption, pathFormatReturn, enumerateOptions ); - } - - #endregion - - #region EnumerateFiles - /// - /// Returns an enumerable collection of files in a specified path. - /// - /// Search pattern. Uses Win32 native filtering. - /// Specifiy depth with - /// Options - /// An enumerable collection of the full names (including paths) for the files in the directory specified by path. - public IEnumerable EnumerateFiles( String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( pattern ) ); - Contract.Ensures(Contract.Result>() != null); - - return QuickIODirectory.EnumerateFiles( FullNameUnc, pattern, searchOption ); - } - - #endregion - - #region EnumerateFileSystemEntryInfos - /// - /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories. - /// - /// Search pattern. Uses Win32 native filtering. - /// Specifiy depth with - /// Options - /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. - /// Requires .NET 4.0 or higher
Warning: parallel file system browsing on the same hard disk (HDD/SSD) will decrease performance. Use this only on stripped RAIDs or with network shares.
- public IEnumerable EnumerateFileSystemEntries( String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( pattern ) ); - Contract.Ensures( Contract.Result>() != null ); - - return QuickIODirectory.EnumerateFileSystemEntries( FullNameUnc, pattern, searchOption, enumerateOptions ); - } - - /// - /// Returns an enumerable collection of file names and directory names that match a search pattern in a specified path, and optionally searches subdirectories. - /// - /// Search pattern. Uses Win32 native filtering. - /// One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.The default value is TopDirectoryOnly. - /// Options - /// An enumerable collection of file-system entries in the directory specified by path and that match the specified search pattern and option. - public IEnumerable EnumerateFileSystemEntryInfos( String pattern = QuickIOPatterns.PathMatchAll, SearchOption searchOption = SearchOption.TopDirectoryOnly, QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( pattern ) ); - Contract.Ensures( Contract.Result>() != null ); - - return EnumerateFileSystemEntries( pattern, searchOption, enumerateOptions ); - } - #endregion - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectoryInfo.Metadata.cs b/src/SchwabenCode.QuickIO/QuickIODirectoryInfo.Metadata.cs deleted file mode 100644 index 31ab95e..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectoryInfo.Metadata.cs +++ /dev/null @@ -1,20 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIODirectoryInfo - { - // TODO: - ///// - ///// Receives of current file - ///// - ///// - //public QuickIODirectoryMetadata GetMetadata( QuickIOEnumerateOptions enumerateOptions = QuickIOEnumerateOptions.None ) - //{ - // return QuickIOEngine.EnumerateDirectoryMetadata( FullNameUnc, FindData, enumerateOptions ); - //} - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectoryInfo.Operators.cs b/src/SchwabenCode.QuickIO/QuickIODirectoryInfo.Operators.cs deleted file mode 100644 index 9d90441..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectoryInfo.Operators.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System.IO; - -namespace SchwabenCode.QuickIO -{ - public sealed partial class QuickIODirectoryInfo - { - /// - /// Returns a of the current path of this folder - /// - /// - public DirectoryInfo AsDirectoryInfo() - { - return new DirectoryInfo( base.FullName ); - } - - /// - /// Explizit Cast - /// - /// - /// - public static explicit operator QuickIODirectoryInfo( DirectoryInfo directoryInfo ) - { - return new QuickIODirectoryInfo( directoryInfo.FullName ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectoryInfo.cs b/src/SchwabenCode.QuickIO/QuickIODirectoryInfo.cs deleted file mode 100644 index fb4a1e3..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectoryInfo.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - /// - /// Provides properties and instance methods for directories - /// - public sealed partial class QuickIODirectoryInfo : QuickIOFileSystemEntryBase - { - #region CTOR - - /// - /// Create new instance of - /// - public QuickIODirectoryInfo( String path ) - : this( new QuickIOPathInfo( QuickIOPath.GetFullPath( path ) ) ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - } - - /// - /// Create new instance of - /// - public QuickIODirectoryInfo( System.IO.DirectoryInfo directoryInfo ) - : this( new QuickIOPathInfo( directoryInfo.FullName ) ) - { - Contract.Requires( directoryInfo != null ); - } - - /// - /// Create new instance of - /// - public QuickIODirectoryInfo( QuickIOPathInfo pathInfo ) - : this( pathInfo, pathInfo.IsRoot ? null : pathInfo.FindData ) - { - Contract.Requires( pathInfo != null ); - } - - /// - /// Creates the folder information on the basis of the path and the handles - /// - /// - /// - internal QuickIODirectoryInfo( QuickIOPathInfo pathInfo, Win32FindData win32FindData ) : - base( pathInfo, win32FindData ) - { - - } - - /// - /// Creates the folder information on the basis of the path and the handles - /// - /// Full path to the directory - /// - internal QuickIODirectoryInfo( String fullname, Win32FindData win32FindData ) - : this( new QuickIOPathInfo( fullname ), win32FindData ) - { - - } - - - #endregion - - #region Properties - /// - /// Returns true if current path is root - /// - public Boolean IsRoot => PathInfo.IsRoot; - - #endregion - - /// - /// Returns true if directory exists. Result starts a file system call and is not cached. - /// - /// Path exists but it's a file.. - public override Boolean Exists => QuickIODirectory.Exists( this ); - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODirectoryMetadata.cs b/src/SchwabenCode.QuickIO/QuickIODirectoryMetadata.cs deleted file mode 100644 index 9105da5..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODirectoryMetadata.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - /// - /// Directory metadata information - /// - public sealed class QuickIODirectoryMetadata : QuickIOFileSystemMetadataBase - { - /// - /// Creates instance of - /// - /// Win32FindData of current directory - /// Directories in current directory - /// Files in current directory - /// UNC Path of current directory - internal QuickIODirectoryMetadata( string uncFullname, Win32FindData win32FindData, IList subDirs, IList subFiles ) - : base( uncFullname , win32FindData ) - { - Directories = new ReadOnlyCollection( subDirs ); - Files = new ReadOnlyCollection( subFiles ); - } - - /// - /// Directories in current directory - /// - public ReadOnlyCollection Directories { get; internal set; } - - /// - /// Files in current directory - /// - public ReadOnlyCollection Files { get; internal set; } - - private UInt64? _bytes; - /// - /// Size of the file. - /// - public UInt64 Bytes - { - get - { - if ( _bytes == null ) - { - UInt64 bytes = 0; - - #region Dirs - - { - for ( int i = 0 ; i < Directories.Count ; i++ ) - { - bytes += +Directories[ i ].Bytes; - } - } - - #endregion - - #region Files - { - for ( int i = 0 ; i < Files.Count ; i++ ) - { - bytes += +Files[ i ].Bytes; - } - } - #endregion - - _bytes = bytes; - } - return ( UInt64 ) _bytes; - } - } - - /// - /// Returns a new instance of of the current directory - /// - /// - public QuickIODirectoryInfo ToDirectoryInfo() - { - return new QuickIODirectoryInfo( ToPathInfo( ) ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIODiskInformation.cs b/src/SchwabenCode.QuickIO/QuickIODiskInformation.cs deleted file mode 100644 index 3caec0d..0000000 --- a/src/SchwabenCode.QuickIO/QuickIODiskInformation.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; - -namespace SchwabenCode.QuickIO -{ - /// - /// Disk metadata information - /// - public sealed class QuickIODiskInformation - { - internal QuickIODiskInformation( UInt64 freeBytes, UInt64 totalBytes, UInt64 totalFreeBytes ) - { - FreeBytes = freeBytes; - TotalBytes = totalBytes; - TotalFreeBytes = totalFreeBytes; - } - - /// - /// Total available number of bytes for the user who executed the API call. - /// - public UInt64 FreeBytes { get;} - - /// - /// Total bytes of share - /// - public UInt64 TotalBytes { get; } - - /// - /// Total free bytes for all users - /// - public UInt64 TotalFreeBytes { get; } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/QuickIOFile.Append.cs b/src/SchwabenCode.QuickIO/QuickIOFile.Append.cs deleted file mode 100644 index 8ffaf9a..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFile.Append.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.IO; -using System.Text; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIOFile - { - /// - /// Appends lines by using the specified encoding. - /// If the file does not exist, it creates the file. - /// - /// The file to append the lines to. The file is created if it doesn't exist. - /// The lines to append. - /// The character encoding. - /// http://msdn.microsoft.com/en-us/library/dd383356(v=vs.110).aspx - public static void AppendAllLines( string path, IEnumerable contents, Encoding encoding = null ) - { - Contract.Requires( !string.IsNullOrWhiteSpace( path ) ); - Contract.Requires( contents != null ); - - using( FileStream fileStream = OpenAppendFileStream( path, FileAccess.Write, FileMode.OpenOrCreate, FileShare.Write ) ) - using( StreamWriter streamWriter = new StreamWriter( fileStream, ( encoding ?? Encoding.UTF8 ) ) ) - { - foreach( var line in contents ) - { - streamWriter.WriteLine( line ); - } - } - - } - - /// - /// Appends lines by using the specified encoding. - /// If the file does not exist, it creates the file. - /// - /// The file to append the lines to. The file is created if it doesn't exist. - /// The lines to append. - /// The character encoding. - /// http://msdn.microsoft.com/en-us/library/dd383356(v=vs.110).aspx - public static void AppendAllLines( QuickIOPathInfo pathInfo, IEnumerable contents, Encoding encoding = null ) - { - Contract.Requires( pathInfo != null ); - Contract.Requires( contents != null ); - - AppendAllLines( pathInfo.FullNameUnc, contents, encoding ); - } - - /// - /// Appends the specified string. - /// If the file does not exist, it creates the file. - /// - /// The file to append the specified string to. - /// The string to append to the file. - /// The character encoding. - /// http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx - public static void AppendAllText( string path, string contents, Encoding encoding = null ) - { - Contract.Requires( !string.IsNullOrWhiteSpace( path ) ); - Contract.Requires( contents != null ); - - using( FileStream fileStream = OpenAppendFileStream( path, FileAccess.Write, FileMode.OpenOrCreate, FileShare.Write ) ) - { - var bytes = ( encoding ?? Encoding.UTF8 ).GetBytes( contents ); - fileStream.Write( bytes, 0, bytes.Length ); - } - } - - /// - /// Appends the specified string. - /// If the file does not exist, it creates the file. - /// - /// The file to append the specified string to. - /// The string to append to the file. - /// The character encoding. - /// http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx - public static void AppendAllText( QuickIOPathInfo pathInfo, string contents, Encoding encoding ) - { - Contract.Requires( pathInfo != null ); - Contract.Requires( contents != null ); - - AppendAllText( pathInfo.FullNameUnc, contents, encoding ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFile.Create.cs b/src/SchwabenCode.QuickIO/QuickIOFile.Create.cs deleted file mode 100644 index ff7e602..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFile.Create.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.IO; -using System.Text; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - - public static partial class QuickIOFile - { - /// - /// Creates a new file. - /// - /// The path to the file. - /// - default - /// - default - /// - default - /// - default 0 (none) - /// The specified path already exists. - /// One or more intermediate directories do not exist; this function will only create the final directory in the path. - public static void Create( String fullName, FileAccess fileAccess = FileAccess.Write, FileShare fileShare = FileShare.None, FileMode fileMode = FileMode.Create, FileAttributes fileAttributes = 0 ) - { - QuickIOEngine.CreateFile( fullName, fileAccess, fileShare, fileMode, fileAttributes ); - } - - /// - /// Creates a new file. - /// - /// The path to the file. - /// - default - /// - default - /// - default - /// - default 0 (none) - /// The specified path already exists. - /// One or more intermediate directories do not exist; this function will only create the final directory in the path. - public static void Create( QuickIOPathInfo pathInfo, FileAccess fileAccess = FileAccess.Write, FileShare fileShare = FileShare.None, FileMode fileMode = FileMode.Create, FileAttributes fileAttributes = 0 ) - { - Create( pathInfo.FullNameUnc, fileAccess, fileShare, fileMode, fileAttributes ); - } - - /// - /// Creates or overwrites the specified file. - /// - /// The name of the file. - /// The number of bytes buffered for reads and writes to the file. - /// A with the specified buffer size that provides read/write access to the file specified in path. - /// http://msdn.microsoft.com/en-us/library/981h90e5(v=vs.110).aspx - public static FileStream Create( string path, int bufferSize ) - { - return OpenFileStream( path, FileAccess.ReadWrite, FileMode.Create, FileShare.None, bufferSize ); - - } - - /// - /// Creates or overwrites the specified file. - /// - /// The name of the file. - /// The number of bytes buffered for reads and writes to the file. - /// A with the specified buffer size that provides read/write access to the file specified in path. - /// http://msdn.microsoft.com/en-us/library/981h90e5(v=vs.110).aspx - public static FileStream Create( QuickIOPathInfo pathInfo, int bufferSize ) - { - return Create( pathInfo.FullNameUnc, bufferSize ); - } - - /// - /// Creates or opens a file for writing UTF-8 encoded text. - /// - /// The file. - /// A that writes to the specified file using UTF-8 encoding. - /// http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx - public static StreamWriter CreateText( string path ) - { - return new StreamWriter( OpenFileStream( path, FileAccess.ReadWrite, FileMode.Create, FileShare.None ) ); - } - - /// - /// Creates or opens a file for writing UTF-8 encoded text. - /// - /// The file. - /// A that writes to the specified file using UTF-8 encoding. - /// http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx - public static StreamWriter CreateText( QuickIOPathInfo pathInfo ) - { - return CreateText( pathInfo.FullNameUnc ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFile.Open.cs b/src/SchwabenCode.QuickIO/QuickIOFile.Open.cs deleted file mode 100644 index 7aa9575..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFile.Open.cs +++ /dev/null @@ -1,202 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIOFile - { - /// - /// Opens a - /// - /// The file to open. - /// - /// - /// - /// A - /// http://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx - public static FileStream Open( string path, FileMode mode, FileAccess access, FileShare share ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( Contract.Result() != null ); - - return OpenFileStream( path, access, mode, share ); - } - - /// - /// Opens a - /// - /// The file to open. - /// - /// - /// - /// - /// http://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx - public static FileStream Open( QuickIOPathInfo pathInfo, FileMode mode, FileAccess access, FileShare share ) - { - Contract.Requires( pathInfo != null ); - Contract.Ensures( Contract.Result() != null ); - - return OpenFileStream( pathInfo.FullNameUnc, access, mode, share ); - } - - /// - /// Opens an existing file for reading. - /// - /// The file to be opened for reading. - /// A read-only on the specified path. - /// http://msdn.microsoft.com/en-us/library/system.io.file.openread(v=vs.110).aspx - public static FileStream OpenRead( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( Contract.Result() != null ); - - return OpenFileStream( path, FileAccess.Read ); - } - - /// - /// Opens an existing file for reading. - /// - /// The file to be opened for reading. - /// A read-only on the specified path. - /// http://msdn.microsoft.com/en-us/library/system.io.file.openread(v=vs.110).aspx - public static FileStream OpenRead( QuickIOPathInfo pathInfo ) - { - Contract.Requires( pathInfo != null ); - Contract.Ensures( Contract.Result() != null ); - - return OpenRead( pathInfo.FullNameUnc ); - } - - /// - /// Opens a - /// - public static FileStream OpenFileStream( string path, FileAccess fileAccess, FileMode fileOption = FileMode.Open, FileShare shareMode = FileShare.Read, Int32 buffer = 0 ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( Contract.Result() != null ); - - var fileHandle = Win32SafeNativeMethods.CreateFile( path, fileAccess, shareMode, IntPtr.Zero, fileOption, 0, IntPtr.Zero ); - var win32Error = Marshal.GetLastWin32Error(); - if( fileHandle.IsInvalid ) - { - Win32ErrorCodes.NativeExceptionMapping( path, win32Error ); // Throws an exception - } - - return buffer > 0 ? new FileStream( fileHandle, fileAccess, buffer ) : new FileStream( fileHandle, fileAccess ); - } - - /// - /// Opens a - /// - public static FileStream OpenAppendFileStream( string path, FileAccess fileAccess, FileMode fileOption = FileMode.Open, FileShare shareMode = FileShare.Read, Int32 buffer = 0 ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( Contract.Result() != null ); - - var fileHandle = Win32SafeNativeMethods.CreateFileForAppend( path, 0x0004 /* Internal Win Append Mode*/, shareMode, IntPtr.Zero, fileOption, 0, IntPtr.Zero ); - var win32Error = Marshal.GetLastWin32Error(); - if( fileHandle.IsInvalid ) - { - Win32ErrorCodes.NativeExceptionMapping( path, win32Error ); // Throws an exception - } - - return buffer > 0 ? new FileStream( fileHandle, fileAccess, buffer ) : new FileStream( fileHandle, fileAccess ); - } - - - - /// - /// Opens an existing UTF-8 encoded text file for reading. - /// - /// The file to be opened for reading. - /// A . - /// http://msdn.microsoft.com/en-us/library/system.io.file.opentext(v=vs.110).aspx - public static StreamReader OpenText( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( Contract.Result() != null ); - - return new StreamReader( OpenFileStream( path, FileAccess.ReadWrite, FileMode.Open, FileShare.Read ), Encoding.UTF8 ); - } - - /// - /// Opens an existing UTF-8 encoded text file for reading. - /// - /// The file. - /// A . - /// http://msdn.microsoft.com/en-us/library/system.io.file.opentext(v=vs.110).aspx - public static StreamReader OpenText( QuickIOPathInfo pathInfo ) - { - Contract.Requires( pathInfo != null ); - Contract.Ensures( Contract.Result() != null ); - - return OpenText( pathInfo.FullNameUnc ); - } - - /// - /// Opens an existing file or creates a new file for writing. - /// - /// The file. - /// An unshared with Write access. - /// http://msdn.microsoft.com/en-us/library/system.io.file.openwrite(v=vs.110).aspx - public static FileStream OpenWrite( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( Contract.Result() != null ); - - return OpenFileStream( path, FileAccess.ReadWrite, FileMode.OpenOrCreate, FileShare.None ); - } - - /// - /// Opens an existing file or creates a new file for writing. - /// - /// The file. - /// An unshared with Write access. - /// http://msdn.microsoft.com/en-us/library/system.io.file.openwrite(v=vs.110).aspx - public static FileStream OpenWrite( QuickIOPathInfo pathInfo ) - { - Contract.Requires( pathInfo != null ); - Contract.Ensures( Contract.Result() != null ); - - return OpenWrite( pathInfo.FullNameUnc ); - } - - /// - /// Opens an existing file or creates a new file for appending. - /// - /// The file. - /// An unshared with Write access. - /// http://msdn.microsoft.com/en-us/library/system.io.file.openwrite(v=vs.110).aspx - public static FileStream OpenAppend( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( Contract.Result() != null ); - - return OpenFileStream( path, FileAccess.ReadWrite, FileMode.Append, FileShare.None ); - - } - - /// - /// Opens an existing file or creates a new file for appending. - /// - /// The file. - /// An unshared with Write access. - /// http://msdn.microsoft.com/en-us/library/system.io.file.openwrite(v=vs.110).aspx - public static FileStream OpenAppend( QuickIOPathInfo pathInfo ) - { - Contract.Requires( pathInfo != null ); - Contract.Ensures( Contract.Result() != null ); - - return OpenAppend( pathInfo.FullNameUnc ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFile.Read.cs b/src/SchwabenCode.QuickIO/QuickIOFile.Read.cs deleted file mode 100644 index 596cc44..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFile.Read.cs +++ /dev/null @@ -1,150 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIOFile - { - /// - /// Opens a binary file, reads the contents of the file into a byte array, and then closes the file. - /// - /// The file to open for reading. - /// A byte array containing the contents of the file. - /// http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes(v=vs.110).aspx - public static byte[ ] ReadAllBytes( string path ) - { - return ReadAllBytes( new QuickIOPathInfo( path ) ); - } - - /// - /// Reads the contents of the file into a byte collection. - /// - /// The file. - /// Read buffer byte size - /// A byte collection containing the contents. - /// http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes(v=vs.110).aspx - public static byte[ ] ReadAllBytes( QuickIOPathInfo pathInfo, Int32 readBuffer = 1024 ) - { - using ( var readStream = OpenRead( pathInfo ) ) - { - var buffer = new byte[ readBuffer ]; - using ( var ms = new MemoryStream( ) ) - { - int read; - while ( ( read = readStream.Read( buffer, 0, buffer.Length ) ) > 0 ) - { - ms.Write( buffer, 0, read ); - } - return ms.ToArray( ); - } - } - } - - /// - /// Reads all lines. - /// - /// The file. - /// A string collection containing all lines. - /// http://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx - public static IEnumerable ReadAllLines( string path ) - { - return ReadAllLines( path, Encoding.UTF8 ); - } - - /// - /// Reads all lines. - /// - /// The file. - /// A string collection containing all lines. - /// http://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx - public static IEnumerable ReadAllLines( QuickIOPathInfo pathInfo ) - { - return ReadAllLines( pathInfo, Encoding.UTF8 ); - } - - /// - /// Reads all lines with the specified encoding - /// - /// The file. - /// The encoding applied to the contents. - /// A string collection containing all lines. - /// http://msdn.microsoft.com/en-us/library/bsy4fhsa(v=vs.110).aspx - public static IEnumerable ReadAllLines( string path, Encoding encoding ) - { - return ReadAllLines( new QuickIOPathInfo( path ), encoding ); - } - - /// - /// Reads all lines with the specified encoding - /// - /// The file. - /// The encoding applied to the contents. - /// A string collection containing all lines. - /// http://msdn.microsoft.com/en-us/library/bsy4fhsa(v=vs.110).aspx - public static IEnumerable ReadAllLines( QuickIOPathInfo pathInfo, Encoding encoding ) - { - using ( var streamReader = new StreamReader( OpenRead( pathInfo.FullNameUnc ), encoding ) ) - { - while ( streamReader.Peek( ) >= 0 ) - { - yield return streamReader.ReadLine( ); - } - } - } - - /// - /// Reads all text. - /// - /// The file. - /// A string represents the content. - /// http://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx - public static string ReadAllText( string path ) - { - return ReadAllText( new QuickIOPathInfo( path ) ); - } - - /// - /// Reads all text. - /// - /// The file. - /// A string represents the content. - public static string ReadAllText( QuickIOPathInfo pathInfo ) - { - return ReadAllText( pathInfo, Encoding.UTF8 ); - } - - /// - /// Reads all text with the specified encoding. - /// - /// The file. - /// The encoding applied to the content. - /// A string represents the content. - /// http://msdn.microsoft.com/en-us/library/ms143369(v=vs.110).aspx - public static string ReadAllText( string path, Encoding encoding ) - { - return ReadAllText( new QuickIOPathInfo( path ), encoding ); - } - - /// - /// Reads all text with the specified encoding. - /// - /// The file. - /// The encoding applied to the content. - /// A string represents the content. - /// http://msdn.microsoft.com/en-us/library/ms143369(v=vs.110).aspx - public static string ReadAllText( QuickIOPathInfo pathInfo, Encoding encoding ) - { - using ( var streamReader = new StreamReader( OpenRead( pathInfo.FullNameUnc ), encoding ) ) - { - return streamReader.ReadToEnd( ); - } - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFile.Write.cs b/src/SchwabenCode.QuickIO/QuickIOFile.Write.cs deleted file mode 100644 index d6c74f8..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFile.Write.cs +++ /dev/null @@ -1,128 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.IO; -using System.Linq; -using System.Text; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIOFile - { - - /// - /// Writes the specified byte array. - /// If the file already exists, it is overwritten. - /// - /// The file. - /// The bytes to write. - /// http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes(v=vs.110).aspx - public static void WriteAllBytes( string path, byte[] bytes ) - { - Contract.Requires( !string.IsNullOrWhiteSpace( path ) ); - Contract.Requires( bytes != null ); - - using( var fileStream = OpenFileStream( path, FileAccess.ReadWrite, FileMode.Create, FileShare.None ) ) - { - fileStream.Seek( 0, SeekOrigin.Begin ); - fileStream.Write( bytes, 0, bytes.Length ); - } - } - - /// - /// Writes the specified byte array. - /// If the file already exists, it is overwritten. - /// - /// The file. - /// The bytes to write. - /// http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes(v=vs.110).aspx - public static void WriteAllBytes( QuickIOPathInfo pathInfo, IEnumerable bytes ) - { - Contract.Requires( pathInfo != null ); - Contract.Requires( bytes != null ); - - WriteAllBytes( pathInfo.FullNameUnc, bytes.ToArray() ); - } - - - - - /// - /// Writes a collection of strings. - /// - /// The file. - /// The lines write to. - /// The character encoding to use. - /// http://msdn.microsoft.com/en-us/library/dd383463(v=vs.110).aspx - public static void WriteAllLines( string path, IEnumerable contents, Encoding encoding = null ) - { - Contract.Requires( !string.IsNullOrWhiteSpace( path ) ); - Contract.Requires( contents != null ); - - using( var fileStream = OpenFileStream( path, FileAccess.ReadWrite, FileMode.Create, FileShare.None ) ) - using( var streamWriter = new StreamWriter( fileStream, ( encoding ?? Encoding.UTF8 ) ) ) - { - foreach( var entry in contents ) - { - streamWriter.WriteLine( entry ); - } - } - } - - /// - /// Writes a collection of strings. - /// - /// The file. - /// The lines write to. - /// The character encoding to use. - /// http://msdn.microsoft.com/en-us/library/dd383463(v=vs.110).aspx - public static void WriteAllLines( QuickIOPathInfo pathInfo, IEnumerable contents, Encoding encoding = null ) - { - Contract.Requires( pathInfo != null ); - Contract.Requires( contents != null ); - - WriteAllLines( pathInfo.FullNameUnc, contents, encoding ); - } - - - /// - /// Writes the specified string. - /// If the target file already exists, it is overwritten. - /// - /// The file. - /// The string to write to. - /// The encoding to apply to the string. - /// http://msdn.microsoft.com/en-us/library/ms143376(v=vs.110).aspx - public static void WriteAllText( string path, string contents, Encoding encoding = null) - { - Contract.Requires( !string.IsNullOrWhiteSpace( path ) ); - Contract.Requires( contents != null ); - - using( var fileStream = OpenFileStream( path, FileAccess.ReadWrite, FileMode.Create, FileShare.None ) ) - using( var streamWriter = new StreamWriter( fileStream, (encoding ?? Encoding.UTF8) ) ) - { - streamWriter.Write( contents ); - } - } - - /// - /// Writes the specified string. - /// If the target file already exists, it is overwritten. - /// - /// The file. - /// The string to write to. - /// The encoding to apply to the string. - /// http://msdn.microsoft.com/en-us/library/ms143376(v=vs.110).aspx - public static void WriteAllText( QuickIOPathInfo pathInfo, string contents, Encoding encoding = null ) - { - Contract.Requires( pathInfo != null ); - Contract.Requires( contents != null ); - - WriteAllText(pathInfo.FullNameUnc, contents, encoding); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFile.cs b/src/SchwabenCode.QuickIO/QuickIOFile.cs deleted file mode 100644 index db0b7ce..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFile.cs +++ /dev/null @@ -1,215 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.IO; -using System.Diagnostics.Contracts; -using SchwabenCode.QuickIO.Engine; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - /// - /// Provides static methods to access files. For example creating, deleting and retrieving content and security information such as the owner. - /// - public static partial class QuickIOFile - { - - /// - /// Copies an existing file. Overwrites an existing file if is true - /// - /// The file to copy. - /// Target directory - /// New File name. Null or empty to use 's name - /// true to overwrite existing file - /// http://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx - /// Filesystem is busy - public static void CopyToDirectory( string sourceFileName, string targetDirectory, String newFileName = null, Boolean overwrite = false ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( sourceFileName ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( targetDirectory ) ); - - if( String.IsNullOrWhiteSpace( sourceFileName ) ) - { - throw new ArgumentNullException( nameof( sourceFileName ) ); - } - if( String.IsNullOrWhiteSpace( targetDirectory ) ) - { - throw new ArgumentNullException( nameof( targetDirectory ) ); - } - - // determine filename - string targetFileName; - if( !String.IsNullOrWhiteSpace( newFileName ) ) - { - // TODO: Check for invalid chars - targetFileName = newFileName; - } - else - { - targetFileName = QuickIOPath.GetName( sourceFileName ); - } - - Copy( sourceFileName, QuickIOPath.Combine( targetDirectory, targetFileName ), overwrite ); - - } - - /// - /// Copies an existing file. Overwrites an existing file if is true - /// - /// The file to copy. - /// Target directory - /// New File name. Null or empty to use ' name - /// true to overwrite existing files - /// http://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx - /// Filesystem is busy - public static void CopyToDirectory( QuickIOFileInfo sourceFileName, QuickIODirectoryInfo targetDirectory, String newFileName = null, Boolean overwrite = false ) - { - Contract.Requires( sourceFileName != null ); - Contract.Requires( targetDirectory != null ); - - if( sourceFileName == null ) - { - throw new ArgumentNullException( nameof( sourceFileName ) ); - } - if( targetDirectory == null ) - { - throw new ArgumentNullException( nameof( targetDirectory ) ); - } - - CopyToDirectory( sourceFileName.FullNameUnc, targetDirectory.FullNameUnc, newFileName, overwrite ); - } - - /// - /// Copies an existing file. Overwrites an existing file if is true - /// - /// The file to copy. - /// Target file - /// true to overwrite existing files - /// Creates parent path if not exists. Decreases copy performance - /// http://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx - /// Filesystem is busy - public static void Copy( string source, string target, Boolean overwrite = false, Boolean createRecursive = true ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( source ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( target ) ); - - if( String.IsNullOrWhiteSpace( source ) ) - { - throw new ArgumentNullException( nameof( source ) ); - } - if( String.IsNullOrWhiteSpace( target ) ) - { - throw new ArgumentNullException( nameof( target ) ); - } - - if( createRecursive ) - { - var targetDirectoryPath = QuickIOPath.GetDirectoryName( target ); - try - { - QuickIODirectory.Create( targetDirectoryPath, true ); - } - catch( PathAlreadyExistsException ) - { - // yay ignore this! - } - } - - int win32Error; - if( !QuickIOEngine.CopyFile( source, target, out win32Error, overwrite ) ) - { - Win32ErrorCodes.NativeExceptionMapping( !Exists( source ) ? target : target, win32Error ); - } - } - - /// - /// Deletes the file. - /// - /// The fullname of the file to be deleted. - /// http://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx - /// File does not exist. - public static void Delete( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - QuickIOEngine.DeleteFile( path ); - } - - - /// - /// Checks whether the specified file exists. - /// - /// The path to check. - /// true if the caller has the required permissions and path contains the name of an existing file; otherwise, false - /// The original Exists method returns also false on null! http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx - /// Searched for file but found folder. - /// Path is invalid. - public static bool Exists( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - return QuickIOEngine.FileExists( path ); - } - - /// - /// Checks whether the specified file exists. - /// - /// The the file to check. - /// true if the caller has the required permissions and path contains the name of an existing file; otherwise, false - /// The original Exists method returns also false on null! http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx - /// Searched for file but found folder. - /// Path is invalid. - public static bool Exists( QuickIOFileInfo fileInfo ) - { - Contract.Requires( fileInfo != null ); - - return Exists( fileInfo.FullNameUnc ); - } - - /// - /// Moves a specified file to a new location, providing the option to give a new file name. - /// - /// The name of the file to move. - /// The new path for the file. Parent directory must exist. - /// http://msdn.microsoft.com/en-us/library/system.io.file.move(v=vs.110).aspx - public static void Move( string sourceFileName, string destinationFileName ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( sourceFileName ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( destinationFileName ) ); - - QuickIOEngine.MoveFile( sourceFileName, destinationFileName ); - } - - /// - /// Moves a file, providing the option to give a new file name. - /// - /// The file to move. - /// Target directory to move the file. - /// http://msdn.microsoft.com/en-us/library/system.io.file.move(v=vs.110).aspx - public static void Move( QuickIOPathInfo sourceFileInfo, QuickIOPathInfo destinationFolder ) - { - Contract.Requires( sourceFileInfo != null ); - Contract.Requires( destinationFolder != null ); - - QuickIOEngine.MoveFile( sourceFileInfo.FullNameUnc, Path.Combine( destinationFolder.FullNameUnc, sourceFileInfo.Name ) ); - } - - /// - /// Moves a file, providing the option to give a new file name. - /// - /// The file to move. - /// Target directory to move the file. - /// http://msdn.microsoft.com/en-us/library/system.io.file.move(v=vs.110).aspx - public static void Move( QuickIOPathInfo sourceFileInfo, QuickIODirectoryInfo destinationFolder ) - { - Contract.Requires( sourceFileInfo != null ); - Contract.Requires( destinationFolder != null ); - - QuickIOEngine.MoveFile( sourceFileInfo.FullNameUnc, Path.Combine( destinationFolder.FullNameUnc, sourceFileInfo.Name ) ); - } - - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFileChunk.cs b/src/SchwabenCode.QuickIO/QuickIOFileChunk.cs deleted file mode 100644 index b493cd1..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileChunk.cs +++ /dev/null @@ -1,117 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Security.Cryptography; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - /// - /// Represents a file chunk - /// - public sealed class QuickIOFileChunk - { - /// - /// Start position - /// - public UInt64 Position { get; } - /// - /// Bytes - /// - public Byte[ ] Bytes { get; } - - /// - /// Represents a file chunk - /// - /// Start position - /// Bytes - public QuickIOFileChunk( UInt64 position, Byte[ ] bytes ) - { - Position = position; - Bytes = bytes; - } - - /// - /// First then . - /// Does not overwrite default method! - /// - /// Chunks to verify with - /// Returns true if both executed methods are true - public bool ChunkEquals( QuickIOFileChunk chunk ) - { - Contract.Requires( chunk != null ); - return ( InternalPositionEquals( chunk ) && BytesEquals( chunk ) ); - } - - /// - /// Checks - /// - /// Chunks to verify with - /// True if both position equals - public bool PositionEquals( QuickIOFileChunk chunk ) - { - Contract.Requires( chunk != null ); - return InternalPositionEquals( chunk ); - } - /// - /// Internal usage. Does not verify parameter. - /// - private bool InternalPositionEquals( QuickIOFileChunk chunk ) - { - return ( Position == chunk.Position ); - } - - /// - /// Checks - /// - /// Chunks to verify with - /// True if both bytes equals. Uses - /// IEnumerable.SequenceEqual - /// - /// - public bool BytesEquals( QuickIOFileChunk chunk ) - { - Contract.Requires( chunk != null ); - return InternalBytesEquals( chunk ); - } - /// - /// Internal usage. Does not verify parameter. - /// - private bool InternalBytesEquals( QuickIOFileChunk chunk ) - { - // First check length - if( Bytes.Length != chunk.Bytes.Length ) - { - return false; - } - - // then check elements - for( int i = 0 ;i < Bytes.Length ;i++ ) - { - if( Bytes[ i ] != chunk.Bytes[ i ] ) - { - return false; - } - } - - return true; - } - - - - - /// - /// File chunk hash calculation - /// - /// - public QuickIOHashResult CalculateHash( HashAlgorithm algorithm ) - { - Contract.Ensures( Contract.Result() != null ); - - return QuickIOHash.Calculate( algorithm, Bytes ); - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Append.cs b/src/SchwabenCode.QuickIO/QuickIOFileInfo.Append.cs deleted file mode 100644 index b3bf459..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Append.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System.Collections.Generic; -using System.Text; - - -namespace SchwabenCode.QuickIO -{ - public sealed partial class QuickIOFileInfo - { - /// - /// Appends lines to a file. - /// Uses UTF-8 Encoding. - /// - /// The lines to append. - public void AppendAllLines( IEnumerable contents ) - { - QuickIOFile.AppendAllLines( PathInfo, contents, Encoding.UTF8 ); - } - - /// - /// Appends lines by using the specified encoding. - /// If the file does not exist, it creates the file. - /// - /// The lines to append. - /// The character encoding. - public void AppendAllLines( IEnumerable contents, Encoding encoding ) - { - QuickIOFile.AppendAllLines( PathInfo, contents, encoding ); - } - - /// - /// Appends the specified string. - /// If the file does not exist, it creates the file. - /// Uses UTF-8 Encoding. - /// - /// The string to append to the file. - /// http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx - public void AppendAllText( string contents ) - { - QuickIOFile.AppendAllText( PathInfo, contents, Encoding.UTF8 ); - } - - /// - /// Appends the specified string. - /// If the file does not exist, it creates the file. - /// - /// The string to append to the file. - /// The character encoding. - /// http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx - public void AppendAllText( string contents, Encoding encoding ) - { - QuickIOFile.AppendAllText( PathInfo, contents, encoding ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Chunks.cs b/src/SchwabenCode.QuickIO/QuickIOFileInfo.Chunks.cs deleted file mode 100644 index c4664f6..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Chunks.cs +++ /dev/null @@ -1,174 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using System.IO; - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIOFileInfo - { - /// - /// Default ChunkSize - /// - private const Int32 DefaultChunkSize = 1024; // Bytes - - - /// - /// Returns the file chunks by given chunksize - /// - /// Chunk size (Bytes) - /// Collection of chunks. On enumerator, the file gets read. - public IEnumerable GetFileChunks( Int32 chunkSize = DefaultChunkSize ) - { - return InternalEnumerateFileChunks( chunkSize ); - } - - /// - /// Returns the chunks of current file that are identical with the other file - /// - /// File to compare - /// Chunk size (Bytes) - /// Returns the chunks of current file that are identical with the other file - public IEnumerable GetFileChunksEqual( QuickIOFileInfo file, Int32 chunkSize = DefaultChunkSize ) - { - var en1 = GetFileChunksEnumerator( chunkSize ); - var en2 = file.GetFileChunksEnumerator( chunkSize ); - - while ( en1.MoveNext( ) && en2.MoveNext( ) ) - { - // check of the chunks are equal - if ( en1.Current.ChunkEquals( en2.Current ) ) - { - // equal - yield return en1.Current; - } - } - } - - /// - /// Returns the chunks of current file that are NOT identical with the other file - /// - /// File to compare - /// Chunk size (Bytes) - /// Returns the chunks of current file that are NOT identical with the other file - public IEnumerable GetFileChunksUnequal( QuickIOFileInfo file, Int32 chunkSize = DefaultChunkSize ) - { - var en1 = GetFileChunksEnumerator( chunkSize ); - var en2 = file.GetFileChunksEnumerator( chunkSize ); - - while ( en1.MoveNext( ) ) - { - var mn2 = en2.MoveNext( ); - - // EOF of file2? - if ( !mn2 ) - { - // current chunk must be unequal - yield return en1.Current; - } - else - { - // check of the chunks are unequal - if ( !en1.Current.ChunkEquals( en2.Current ) ) - { - // unequal - yield return en1.Current; - } - } - } - } - - /// - /// Returns the - /// IEnumerator - /// of - /// - /// Chunk size (Bytes) - /// - public IEnumerator GetFileChunksEnumerator( Int32 chunkSize = DefaultChunkSize ) - { - return GetFileChunks( chunkSize ).GetEnumerator( ); - } - - /// - /// Checks if both file contents are equal. - /// Opens both files for read and breaks on first unequal chunk. - /// - /// File to compare - /// Chunk size (Bytes) - /// true if contents are equal - public Boolean IsEqualContents( QuickIOFileInfo file, Int32 chunkSize = DefaultChunkSize ) - { - var en1 = GetFileChunksEnumerator( chunkSize ); - var en2 = file.GetFileChunksEnumerator( chunkSize ); - - while ( true ) - { - // Go to next element - var mn1 = en1.MoveNext( ); - var mn2 = en2.MoveNext( ); - - // check if next element exists - if ( mn1 != mn2 ) - { - // collections count diff - return false; - } - - // no more elements in both collections - if ( !mn1 ) - { - return true; - } - - // check chunks - var chunk1 = en1.Current; - var chunk2 = en2.Current; - - if ( !chunk1.ChunkEquals( chunk2 ) ) - { - return false; - } - } - } - - /// - /// Reads the file and returns containign chunks - /// - /// Chunk size (Bytes) - /// Collection of chunks - private IEnumerable InternalEnumerateFileChunks( Int32 chunkSize = DefaultChunkSize ) - { - FileStream fs; - try - { - // Open first File - fs = OpenRead( ); - } - catch ( Exception e ) - { - throw new Exception( "Failed to file to read", e ); - } - - using ( fs ) - { - // check buffer for small files; will be faster - var bytes = new byte[ Math.Min( fs.Length, chunkSize ) ]; - - UInt64 position = 0; - // transfer chunks - while ( ( fs.Read( bytes, 0, bytes.Length ) ) > 0 ) - { - //var arr = new byte[ bytes.Length ]; - //Buffer.BlockCopy( bytes, 0, arr, 0, bytes.Length ); - yield return new QuickIOFileChunk( position, bytes ); - position += Convert.ToUInt64( bytes.Length ); - } - } - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Compare.Timestamps.cs b/src/SchwabenCode.QuickIO/QuickIOFileInfo.Compare.Timestamps.cs deleted file mode 100644 index a555618..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Compare.Timestamps.cs +++ /dev/null @@ -1,113 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIOFileInfo - { - /// - /// Returns the if all timestamps are equal - /// - /// File to compare with - /// Returns the if all timestamps are equal - public Boolean IsEqualTimestamps( QuickIOFileInfo file ) - { - Contract.Requires( file != null ); - return ( InternalIsEqualTimestampCreated( file ) && InternalIsEqualTimestampLastAccessed( file ) && InternalIsEqualTimestampsLastWritten( file ) ); - } - - /// - /// Checks all timestamps. - /// - /// File to compare with - /// If collection is empty, all timestamps are equal. Otherwise unequal timestamp is returned. - public IEnumerable CompareTimestamps( QuickIOFileInfo file ) - { - Contract.Requires( file != null ); - - if ( InternalIsEqualTimestampCreated( file ) ) - { - yield return QuickIOFileCompareCriteria.TimestampCreated; - } - - if ( InternalIsEqualTimestampLastAccessed( file ) ) - { - yield return QuickIOFileCompareCriteria.TimestampLastAccessed; - } - - if ( InternalIsEqualTimestampsLastWritten( file ) ) - { - yield return QuickIOFileCompareCriteria.TimestampLastWritten; - } - } - - /// - /// Returns the if timestamp 'created' is equal - /// - /// File to compare with - /// Returns the if timestamp 'created' is equal - public Boolean IsEqualTimestampCreated( QuickIOFileInfo file ) - { - Contract.Requires( file != null ); - return InternalIsEqualTimestampCreated( file ); - } - /// - /// Same as but does not check the param for null - /// - private Boolean InternalIsEqualTimestampCreated( QuickIOFileInfo file ) - { - Contract.Requires( file != null ); - - var result = ( this.CreationTimeUtc.CompareTo( file.CreationTimeUtc ) ); - return ( result == 0 ); // result < 0: file1 is earlier, result > 0: file1 is later. 0 = equal - } - - /// - /// Returns the if timestamp 'last accessed' is equal - /// - /// File to compare with - /// Returns the if timestamp 'last accessed' is equal - public Boolean IsEqualTimestampLastAccessed( QuickIOFileInfo file ) - { - Contract.Requires( file != null ); - return InternalIsEqualTimestampLastAccessed( file ); - } - /// - /// Same as but does not check the param for null - /// - private Boolean InternalIsEqualTimestampLastAccessed( QuickIOFileInfo file ) - { - Contract.Requires( file != null ); - - int result = ( this.LastAccessTimeUtc.CompareTo( file.LastAccessTimeUtc ) ); - return ( result == 0 ); // result < 0: file1 is earlier, result > 0: file1 is later. 0 = equal - } - - /// - /// Returns the if timestamp 'last written to' is equal - /// - /// File to compare with - /// Returns the if timestamp 'last written to' is equal - public Boolean IsEqualTimestampsLastWritten( QuickIOFileInfo file ) - { - Contract.Requires( file != null ); - return InternalIsEqualTimestampsLastWritten( file ); - } - /// - /// Same as but does not check the param for null - /// - private Boolean InternalIsEqualTimestampsLastWritten( QuickIOFileInfo file ) - { - Contract.Requires( file != null ); - - int result = ( this.LastWriteTimeUtc.CompareTo( file.LastWriteTimeUtc ) ); - return ( result == 0 ); // result < 0: file1 is earlier, result > 0: file1 is later. 0 = equal - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Compare.cs b/src/SchwabenCode.QuickIO/QuickIOFileInfo.Compare.cs deleted file mode 100644 index 8898472..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Compare.cs +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIOFileInfo - { - /// - /// Checks byte length (NOT CONTENTS!) - /// - /// File to compare with - /// Returns true if both properties are equal - public Boolean IsEqualByteLength( QuickIOFileInfo file ) - { - Contract.Requires( file != null ); - return ( this.Bytes == file.Bytes ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Compress.cs b/src/SchwabenCode.QuickIO/QuickIOFileInfo.Compress.cs deleted file mode 100644 index 0be58cf..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Compress.cs +++ /dev/null @@ -1,74 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.IO; -using System.IO.Compression; - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIOFileInfo - { - /// - /// Compress all data of file and returns filled - /// - public MemoryStream GetCompressStream( Int32 readBuffer = QuickIORecommendedValues.DefaultReadBufferBytes ) - { - return InternalGetGZipStream( readBuffer, CompressionMode.Compress ); - } - - /// - /// Decompress all data of file and returns filled - /// - public MemoryStream GetDecompressStream( Int32 readBuffer = QuickIORecommendedValues.DefaultReadBufferBytes ) - { - return InternalGetGZipStream( readBuffer, CompressionMode.Decompress ); - } - - /// - /// Internal Usage only - /// - private MemoryStream InternalGetGZipStream( Int32 readBuffer, CompressionMode mode ) - { - var ms = new MemoryStream( ); - - using ( var gZipStream = new GZipStream( ms, mode, true ) ) - { - using ( var readStream = OpenRead( ) ) - { - var buffer = new Byte[ readBuffer ]; - Int32 read; - while ( ( read = readStream.Read( buffer, 0, buffer.Length ) ) > 0 ) - { - gZipStream.Write( buffer, 0, read ); - } - } - } - return ms; - } - - /// - /// Returns all bytes of - /// - public Byte[ ] CompressData() - { - using ( var s = GetCompressStream( ) ) - { - return s.ToArray( ); - } - } - - /// - /// Returns all bytes of - /// - public Byte[ ] DecompressData() - { - using ( var s = GetDecompressStream( ) ) - { - return s.ToArray( ); - } - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Metadata.cs b/src/SchwabenCode.QuickIO/QuickIOFileInfo.Metadata.cs deleted file mode 100644 index 2a9184b..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Metadata.cs +++ /dev/null @@ -1,19 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -namespace SchwabenCode.QuickIO -{ - public sealed partial class QuickIOFileInfo - { - /// - /// Receives of current file - /// - /// - public QuickIOFileMetadata GetMetadata() - { - return new QuickIOFileMetadata( FullNameUnc, FindData ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Open.cs b/src/SchwabenCode.QuickIO/QuickIOFileInfo.Open.cs deleted file mode 100644 index 9349105..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Open.cs +++ /dev/null @@ -1,61 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System.IO; - -namespace SchwabenCode.QuickIO -{ - public sealed partial class QuickIOFileInfo - { - /// - /// Opens a - /// - /// - /// - /// - /// - /// http://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx - public FileStream Open( FileMode mode, FileAccess access = FileAccess.Read, FileShare share = FileShare.None ) - { - return QuickIOFile.Open( FullNameUnc, mode, access, share ); - } - - /// - /// Opens an existing file for reading. - /// - /// A read-only on the specified path. - public FileStream OpenRead() - { - return QuickIOFile.OpenRead( FullNameUnc ); - } - - /// - /// Opens an existing UTF-8 encoded text file for reading. - /// - /// A . - public StreamReader OpenText() - { - return QuickIOFile.OpenText( FullNameUnc ); - } - - /// - /// Opens an existing file or creates a new file for writing. - /// - /// An unshared with Write access. - public FileStream OpenWrite() - { - return QuickIOFile.OpenWrite( FullNameUnc ); - } - - /// - /// Opens an existing file or creates a new file for appending. - /// - /// An unshared with Write access. - public FileStream OpenAppend() - { - return QuickIOFile.OpenAppend( FullNameUnc ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Operators.cs b/src/SchwabenCode.QuickIO/QuickIOFileInfo.Operators.cs deleted file mode 100644 index 8f24025..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Operators.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System.IO; - -namespace SchwabenCode.QuickIO -{ - public sealed partial class QuickIOFileInfo - { - /// - /// Returns a of the current path of this file - /// - /// - public FileInfo AsFileInfo() - { - return new FileInfo( base.FullName ); - } - - /// - /// Explizit Cast - /// - /// - /// - public static explicit operator QuickIOFileInfo( FileInfo fileInfo ) - { - return new QuickIOFileInfo( fileInfo ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Read.cs b/src/SchwabenCode.QuickIO/QuickIOFileInfo.Read.cs deleted file mode 100644 index 8ec1942..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Read.cs +++ /dev/null @@ -1,61 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using System.Text; - -namespace SchwabenCode.QuickIO -{ - public sealed partial class QuickIOFileInfo - { - /// - /// Reads the contents of the file into a byte collection. - /// - /// A byte collection containing the contents. - public byte[ ] ReadAllBytes( Int32 readBuffer = QuickIORecommendedValues.DefaultReadBufferBytes ) - { - return QuickIOFile.ReadAllBytes( PathInfo, readBuffer ); - } - - /// - /// Reads all lines. - /// - /// A string collection containing all lines. - public IEnumerable ReadAllLines() - { - return QuickIOFile.ReadAllLines( PathInfo ); - } - - /// - /// Reads all lines with the specified encoding - /// - /// The encoding applied to the contents. - /// A string collection containing all lines. - public IEnumerable ReadAllLines( Encoding encoding ) - { - return QuickIOFile.ReadAllLines( PathInfo, encoding ); - } - - /// - /// Reads all text. - /// - /// A string represents the content. - public string ReadAllText() - { - return QuickIOFile.ReadAllText( PathInfo ); - } - - /// - /// Reads all text with the specified encoding. - /// - /// The encoding applied to the content. - /// A string represents the content. - public string ReadAllText( Encoding encoding ) - { - return QuickIOFile.ReadAllText( PathInfo, encoding ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Write.cs b/src/SchwabenCode.QuickIO/QuickIOFileInfo.Write.cs deleted file mode 100644 index 7fb925a..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileInfo.Write.cs +++ /dev/null @@ -1,71 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System.Collections.Generic; -using System.Text; - -namespace SchwabenCode.QuickIO -{ - public sealed partial class QuickIOFileInfo - { - - /// - /// Writes the specified byte array. - /// - /// The bytes to write. - public void WriteAllBytes( IEnumerable bytes ) - { - QuickIOFile.WriteAllBytes( PathInfo, bytes ); - } - - /// - /// Writes the specified byte array. - /// - /// The bytes to write. - public void WriteAllBytes( byte[ ] bytes ) - { - QuickIOFile.WriteAllBytes( PathInfo, bytes ); - } - - /// - /// Writes a collection of strings. - /// Uses UTF-8 without Emitted UTF-8 identifier. - /// - /// The lines write to. - public void WriteAllLines( IEnumerable contents ) - { - QuickIOFile.WriteAllLines( PathInfo, contents ); - } - - /// - /// Writes a collection of strings. - /// - /// The lines write to. - /// The character encoding to use. - public void WriteAllLines( IEnumerable contents, Encoding encoding ) - { - QuickIOFile.WriteAllLines( PathInfo, contents, encoding ); - } - - /// - /// Writes the specified string. - /// - /// The string to write to. - /// The encoding to apply to the string. - public void WriteAllText( string contents, Encoding encoding ) - { - QuickIOFile.WriteAllText( PathInfo, contents, encoding ); - } - - /// - /// Writes the specified string. - /// - /// The string to write to. - public void WriteAllText( string contents ) - { - QuickIOFile.WriteAllText( PathInfo, contents ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFileInfo.cs b/src/SchwabenCode.QuickIO/QuickIOFileInfo.cs deleted file mode 100644 index b691b95..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileInfo.cs +++ /dev/null @@ -1,82 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - /// - /// Provides properties and instance methods for files - /// - public sealed partial class QuickIOFileInfo : QuickIOFileSystemEntryBase - { - /// - /// Create new instance of - /// - public QuickIOFileInfo( String path ) - : this( new QuickIOPathInfo( QuickIOPath.GetFullPath( path ) ) ) - { - - } - - /// - /// Create new instance of - /// - public QuickIOFileInfo( System.IO.FileInfo fileInfo ) - : this( new QuickIOPathInfo( fileInfo.FullName ) ) - { - - } - - - /// - /// Create new instance of - /// - public QuickIOFileInfo( QuickIOPathInfo pathInfo ) - : this( pathInfo, pathInfo.FindData ) - { - } - - - /// - /// Creates the file information on the basis of the path and - /// - /// Full path to the file - /// - internal QuickIOFileInfo( String fullName, Win32FindData win32FindData ) - : this( new QuickIOPathInfo( fullName ), win32FindData ) - { - - } - - /// - /// Creates the file information on the basis of the path and - /// - /// Full path to the file - /// - internal QuickIOFileInfo( QuickIOPathInfo pathInfo, Win32FindData win32FindData ) - : base( pathInfo, win32FindData ) - { - - } - - /// - /// Returns true if file exists. Uncached. - /// - /// Path exists but it's a directory. - public override Boolean Exists => QuickIOFile.Exists( this ); - - /// - /// Size of the file. Cached. - /// - public UInt64 Bytes => FindData.GetBytes(); - - /// - /// Size of the file (returns ). - /// - public UInt64 Length => FindData.GetBytes(); - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFileMetadata.cs b/src/SchwabenCode.QuickIO/QuickIOFileMetadata.cs deleted file mode 100644 index 4b1b250..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileMetadata.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - /// - /// File metadata information - /// - public sealed class QuickIOFileMetadata : QuickIOFileSystemMetadataBase - { - /// - /// Creates instance of - /// - /// UNC Path of current file - /// Win32FindData of current file - internal QuickIOFileMetadata( string uncResultPath, Win32FindData win32FindData ) - : base( uncResultPath, win32FindData ) - { - - } - - /// - /// Size of the file. - /// - public UInt64 Bytes => FindData.GetBytes(); - - - /// - /// Returns a new instance of of the current file - /// - /// - public QuickIOFileInfo QuickIOFileInfo() - { - return new QuickIOFileInfo( ToPathInfo() ); - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/QuickIOFileSystemEntry.cs b/src/SchwabenCode.QuickIO/QuickIOFileSystemEntry.cs deleted file mode 100644 index b22600d..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileSystemEntry.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.IO; - -namespace SchwabenCode.QuickIO -{ - /// - /// Represents a file system entry type - /// - public class QuickIOFileSystemEntry - { - /// - /// Creates an instance of - /// - internal QuickIOFileSystemEntry( string path, QuickIOFileSystemEntryType type, FileAttributes attributes, ulong bytes) - { - Contract.Requires( !string.IsNullOrWhiteSpace( path ) ); - Path = path; - Type = type; - Attributes = attributes; - Bytes = bytes; - } - - /// - /// Entry's fullname - /// - public String Path { get; } - - /// - /// Returns in unc. - /// - /// - public String GetPathUnc() - { - return QuickIOPath.ToPathUnc(Path); - } - - /// - /// Returns in regular. - /// - /// - public String GetPathRegular() - { - return QuickIOPath.ToPathRegular( Path ); - } - - /// - /// Entry type - /// - public QuickIOFileSystemEntryType Type { get; } - - /// - /// Entry type - /// - public FileAttributes Attributes { get; } /// - /// Entry type - /// - public ulong Bytes { get; } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/QuickIOFileSystemEntryBase.cs b/src/SchwabenCode.QuickIO/QuickIOFileSystemEntryBase.cs deleted file mode 100644 index a1e73d2..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileSystemEntryBase.cs +++ /dev/null @@ -1,286 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.ComponentModel; -using System.IO; -using System.Security.Principal; -using SchwabenCode.QuickIO.Engine; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - /// - /// Provides properties and instance method for files and directories - /// - [Browsable(false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public abstract class QuickIOFileSystemEntryBase - { - #region Base CTOR - - /// - /// Initializes a new instance of the QuickIOAbstractBase class, which acts as a wrapper for a file path. - /// - /// - /// - internal QuickIOFileSystemEntryBase(QuickIOPathInfo pathInfo, Win32FindData findData) - { - this.PathInfo = pathInfo; - this.FindData = findData; - if(findData != null) - { - this.Attributes = findData.dwFileAttributes; - //Changed to allow paths which do not exist: - _lastWriteTimeUtc = FindData.GetLastWriteTimeUtc(); - _lastAccessTimeUtc = findData.GetLastAccessTimeUtc(); - _creationTimeUtc = findData.GetCreationTimeUtc(); - } - - } - #endregion - - - private DateTime _creationTimeUtc; - private DateTime _lastAccessTimeUtc; - private DateTime _lastWriteTimeUtc; - - /// - /// Returns true if exists - /// - public abstract bool Exists { get; } - - - /// - /// True if file is readonly. Cached. - /// - public Boolean IsReadOnly - { - get { return Attributes.Contains(FileAttributes.ReadOnly); } - set - { - Attributes = Attributes.Force(FileAttributes.ReadOnly, value); - - // Commit current attributes - QuickIOEngine.SetAttributes(PathInfo.FullNameUnc, Attributes); - } - } - - - /// - /// QuickIOPathInfo Container - /// - public QuickIOPathInfo PathInfo { get; protected internal set; } - - - /// - /// Returns true if exists and attends the FileSystemType - /// - /// Suppress error message if the path exists but the differs - /// - /// Default return value if is true - /// True or if thrown and is true - public Boolean SafeExists(bool throwExceptionIfFileSystemEntryTypeDiffers = false, bool exceptionValue = false) - { - try - { - return Exists; - } - catch(UnmatchedFileSystemEntryTypeException) - { - if(throwExceptionIfFileSystemEntryTypeDiffers) - { - return exceptionValue; - } - - throw; - } - } - - /// - /// Name of file or directory - /// - public String Name => PathInfo.Name; - - #region Path Properties - /// - /// Full path of the directory or file. - /// - public String FullName => PathInfo.FullName; - - /// - /// Full path of the directory or file (unc format) - /// - public String FullNameUnc => PathInfo.FullNameUnc; - - /// - /// Fullname of Parent. - /// - public String Parent => PathInfo.Parent; - - /// - /// Returns current - /// - /// - public QuickIOFileSystemSecurity GetFileSystemSecurity() - { - return PathInfo.GetFileSystemSecurity(); - } - - /// - /// Returns Root or null if current path is root - /// - public string Root => PathInfo.Root; - - #endregion - - /// - /// Attributes (Cached Value) - /// - public FileAttributes Attributes { get; protected internal set; } - - #region Time Properties - #region UNC Times - /// - /// Gets the creation time (UTC) - /// - public DateTime CreationTimeUtc - { - get - { - if(PathInfo.IsRoot) - { - throw new NotSupportedException("Root directory does not provide time access"); - } - return _creationTimeUtc; - } - protected set - { - if(PathInfo.IsRoot) - { - throw new NotSupportedException("Root directory does not provide time access"); - } - _creationTimeUtc = value; - } - } - - /// - /// Gets the time (UTC) of last access. - /// - public DateTime LastAccessTimeUtc - { - get - { - if(PathInfo.IsRoot) - { - throw new NotSupportedException("Root directory does not provide time access"); - } - return _lastAccessTimeUtc; - } - protected set - { - if(PathInfo.IsRoot) - { - throw new NotSupportedException("Root directory does not provide time access"); - } - _lastAccessTimeUtc = value; - } - } - - /// - /// Gets the time (UTC) was last written to - /// - public DateTime LastWriteTimeUtc - { - get - { - if(PathInfo.IsRoot) - { - throw new NotSupportedException("Root directory does not provide time access"); - } - return _lastWriteTimeUtc; - } - protected set - { - if(PathInfo.IsRoot) - { - throw new NotSupportedException("Root directory does not provide time access"); - } - _lastWriteTimeUtc = value; - } - } - - #endregion - - #region LocalTime - /// - /// Gets the creation time - /// - public DateTime CreationTime { get { return CreationTimeUtc.ToLocalTime(); } } - - /// - /// Gets the time that the file was last accessed - /// - public DateTime LastAccessTime { get { return LastAccessTimeUtc.ToLocalTime(); } } - - /// - /// Gets the time the file was last written to. - /// - public DateTime LastWriteTime { get { return LastWriteTimeUtc.ToLocalTime(); } } - #endregion - #endregion - - #region Overrides - /// - /// Returns - /// - /// - public override string ToString() - { - return FullName; - } - #endregion - - /// - /// Win32ApiFindData bag - /// - internal Win32FindData FindData { get; private set; } - - /// - /// Determines the owner - /// - /// - public NTAccount GetOwner() - { - return PathInfo.GetOwner(); - } - - /// - /// Determines the owner - /// - /// - public IdentityReference GetOwnerIdentifier() - { - return PathInfo.GetOwnerIdentifier(); - } - - /// - /// Determines the owner - /// - /// - public void SetOwner(NTAccount newOwner) - { - PathInfo.SetOwner(newOwner); - } - - /// - /// Sets the owner - /// - public void SetOwner(IdentityReference newOwersIdentityReference) - { - PathInfo.SetOwner(newOwersIdentityReference); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOFileSystemMetadataBase.cs b/src/SchwabenCode.QuickIO/QuickIOFileSystemMetadataBase.cs deleted file mode 100644 index 14d4da7..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileSystemMetadataBase.cs +++ /dev/null @@ -1,101 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.IO; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - /// - /// Abstract class for file system entries such as files and directory. - /// Just for meta data reprentation - /// - public abstract class QuickIOFileSystemMetadataBase - { - internal Win32FindData FindData { get; } - - internal QuickIOFileSystemMetadataBase( string fullPath, Win32FindData win32FindData) - { - Contract.Requires( !String.IsNullOrWhiteSpace( fullPath ) ); - Contract.Requires( win32FindData != null ); - - FindData = win32FindData; - - FullNameUnc = QuickIOPath.ToPathUnc( fullPath ); - FullName = QuickIOPath.ToPathRegular( fullPath ); - - this.LastWriteTimeUtc = win32FindData.GetLastWriteTimeUtc(); - this.LastAccessTimeUtc = win32FindData.GetLastAccessTimeUtc(); - this.CreationTimeUtc = win32FindData.GetCreationTimeUtc(); - - Name = win32FindData.cFileName; - - Attributes = win32FindData.dwFileAttributes; - } - - - /// - /// Path to file or directory (regular format) - /// - public String FullName { get; } - - /// - /// Name of file or directory - /// - public String Name { get; } - /// - /// Path to file or directory (unc format) - /// - public String FullNameUnc { get; } - - #region FileTimes - /// - /// Gets the creation time (UTC) - /// - public DateTime CreationTimeUtc { get; } - /// - /// Gets the creation time - /// - public DateTime CreationTime => CreationTimeUtc.ToLocalTime(); - - /// - /// Gets the time (UTC) of last access. - /// - public DateTime LastAccessTimeUtc { get; } - /// - /// Gets the time that the file was last accessed - /// - public DateTime LastAccessTime => LastAccessTimeUtc.ToLocalTime(); - - /// - /// Gets the time (UTC) was last written to - /// - public DateTime LastWriteTimeUtc { get; } - /// - /// Gets the time the file was last written to. - /// - public DateTime LastWriteTime => LastWriteTimeUtc.ToLocalTime(); - - #endregion - - /// - /// File Attributes - /// - public FileAttributes Attributes { get; internal set; } - - /// - /// Returns a new instance of of the current path - /// - /// - public QuickIOPathInfo ToPathInfo() - { - Contract.Requires( !String.IsNullOrWhiteSpace( FullNameUnc ) ); - Contract.Ensures( !String.IsNullOrWhiteSpace( Contract.Result() ) ); - return new QuickIOPathInfo( FullNameUnc ); - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/QuickIOFileSystemSecurity.cs b/src/SchwabenCode.QuickIO/QuickIOFileSystemSecurity.cs deleted file mode 100644 index 44b0955..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFileSystemSecurity.cs +++ /dev/null @@ -1,648 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.IO; -using System.Runtime.InteropServices; -using System.Security.AccessControl; -using System.Security.Principal; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - /// - /// Provides methods for accessing the security information of files and folders, such as for example the getting and setting of the owner. - /// - public class QuickIOFileSystemSecurity - { - private readonly WindowsIdentity _windowsIdentity; - private readonly QuickIOPathInfo _pathInfo; - - /// - /// Creates new instance of for specified path. - /// Current Windows Identtiy is used. - /// - /// - public QuickIOFileSystemSecurity( QuickIOPathInfo pathInfo ) - : this( pathInfo, WindowsIdentity.GetCurrent() ) - { - Contract.Requires( pathInfo != null ); - } - - /// - /// Supply the path to the file or directory and a user or group. - /// Access checks are done - /// during instantiation to ensure we always have a valid object - /// - /// - /// - public QuickIOFileSystemSecurity( QuickIOPathInfo pathInfo, WindowsIdentity principal ) - { - #region Input Validation - Contract.Requires( pathInfo != null ); - Contract.Requires( principal != null ); - - if( pathInfo == null ) - { - throw new ArgumentNullException( nameof( pathInfo ) ); - } - if( principal == null ) - { - throw new ArgumentNullException( nameof( principal ) ); - } - #endregion Input Validation - - this._pathInfo = pathInfo; - this._windowsIdentity = principal; - - Refresh(); - } - - /// - /// Refreshes the Information - /// - public void Refresh() - { - GetSecurityFromFileSystem(); - ReadSecurityInformation(); - } - - /// - /// Affected Windows IDentity - /// - public WindowsIdentity WindowsIdentity - { - get - { - Contract.Ensures( Contract.Result() != null ); - return _windowsIdentity; - } - } - - /// - /// Affected path - /// - public QuickIOPathInfo PathInfo - { - get - { - Contract.Ensures( Contract.Result() != null ); - return _pathInfo; - } - } - - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedAppendData { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedChangePermissions { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedCreateDirectories { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedCreateFiles { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedDelete { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedDeleteSubdirectoriesAndFiles { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedExecuteFile { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedFullControl { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedListDirectory { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedModify { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedRead { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedReadAndExecute { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedReadAttributes { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedReadData { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedReadExtendedAttributes { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedReadPermissions { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedSynchronize { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedTakeOwnership { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedTraverse { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedWrite { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedWriteAttributes { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedWriteData { get; private set; } - /// - /// Returns true if specified right level is denied - /// - public bool IsDeniedWriteExtendedAttributes { get; private set; } - - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedAppendData { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedChangePermissions { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedCreateDirectories { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedCreateFiles { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedDelete { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedDeleteSubdirectoriesAndFiles { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedExecuteFile { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedFullControl { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedListDirectory { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedModify { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedRead { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedReadAndExecute { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedReadAttributes { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedReadData { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedReadExtendedAttributes { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedReadPermissions { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedSynchronize { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedTakeOwnership { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedTraverse { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedWrite { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedWriteAttributes { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedWriteData { get; private set; } - /// - /// Returns true if specified right level is explizit allowed - /// - public bool IsAllowedWriteExtendedAttributes { get; private set; } - - /// - /// Ermittelt, ob etwas hinzugefügt werden kann (Dateien) - /// - public bool CanAppendData => !IsDeniedAppendData && IsAllowedAppendData; - - /// - /// Ermittelt, ob die Rechte verändert werden dürfen - /// - public bool CanChangePermissions => !IsDeniedChangePermissions && IsAllowedChangePermissions; - - /// - /// Ermittelt, ob neue Ordner hinzugefügt werden dürfen (Ordner) - /// - public bool CanCreateDirectories => !IsDeniedCreateDirectories && IsAllowedCreateDirectories; - - /// - /// Ermittelt, ob neue Dateien hinzugefügt werden dürfen (Ordner) - /// - public bool CanCreateFiles => !IsDeniedCreateFiles && IsAllowedCreateFiles; - - /// - /// Ermittelt, ob etwas gelöscht werden darf (Ordner) - /// - public bool CanDelete => !IsDeniedDelete && IsAllowedDelete; - - /// - /// Ermittelt, ob darunterliegende Ordner und Dateien gelöscht werden dürfen (Ordner) - /// - public bool CanDeleteSubdirectoriesAndFiles => !IsDeniedDeleteSubdirectoriesAndFiles && - IsAllowedDeleteSubdirectoriesAndFiles; - - /// - /// Ermittelt, ob eine Datei ausgeführt werden darf (Dateien) - /// - public bool CanExecuteFile => !IsDeniedExecuteFile && IsAllowedExecuteFile; - - /// - /// Ermittelt, ob die vollständige Kontrolle gewährt ist - /// - public bool CanFullControl => !IsDeniedFullControl && IsAllowedFullControl; - - /// - /// Ermittelt, ob die Ordner aufgelistet werden dürfen (Ordner) - /// - public bool CanListDirectory => !IsDeniedListDirectory && IsAllowedListDirectory; - - /// - /// Ermittelt, ob etwas verändert werden darf - /// - public bool CanModify => !IsDeniedModify && IsAllowedModify; - - /// - /// Ermittelt, ob etwas gelesen werden darf - /// - public bool CanRead => !IsDeniedRead && IsAllowedRead; - - /// - /// Ermittelt, ob gelesen und ausgeführt werden darf - /// - public bool CanReadAndExecute => !IsDeniedReadAndExecute && IsAllowedReadAndExecute; - - /// - /// Ermittelt, ob die Attribute gelesen werden dürfen - /// - public bool CanReadAttributes => !IsDeniedReadAttributes && IsAllowedReadAttributes; - - /// - /// Ermittelt, ob Daten gelesen werden dürfen - /// - public bool CanReadData => !IsDeniedReadData && IsAllowedReadData; - - /// - /// Ermittelt, ob die erweiterten Attribute gelesen werden dürfen - /// - public bool CanReadExtendedAttributes => !IsDeniedReadExtendedAttributes && - IsAllowedReadExtendedAttributes; - - /// - /// Ermittelt, ob die Rechte gelesen werden dürfen - /// - public bool CanReadPermissions => !IsDeniedReadPermissions && IsAllowedReadPermissions; - - /// - /// Ermittelt, ob synchronisiert werden darf - /// - public bool CanSynchronize => !IsDeniedSynchronize && IsAllowedSynchronize; - - /// - /// Ermittelt, ob der Besitzerstatus eingenommen werden darf - /// - public bool CanTakeOwnership => !IsDeniedTakeOwnership && IsAllowedTakeOwnership; - - /// - /// Ermittelt, ob ??????? - /// - public bool CanTraverse => !IsDeniedTraverse && IsAllowedTraverse; - - /// - /// Ermittelt, ob geschrieben werden darf - /// - public bool CanWrite => !IsDeniedWrite && IsAllowedWrite; - - /// - /// Ermittelt, ob Attribute verändert werden dürfen - /// - public bool CanWriteAttributes => !IsDeniedWriteAttributes && IsAllowedWriteAttributes; - - /// - /// Ermittelt, ob Daten geschrieben werden dürfen - /// - public bool CanWriteData => !IsDeniedWriteData && IsAllowedWriteData; - - /// - /// Ermittelt, ob erweiterte Attribute geschrieben werden dürfen - /// - public bool CanWriteExtendedAttributes => !IsDeniedWriteExtendedAttributes && IsAllowedWriteExtendedAttributes; - - #region Initial Read - /// - /// Reads the security information of - /// - private void ReadSecurityInformation() - { - // Receive File System ACL Information - AuthorizationRuleCollection acl = FileSystemSecurityInformation.GetAccessRules( true, true, typeof( SecurityIdentifier ) ); - - ReceiveUserIdentityRules( acl ); - ReceivGroupIdentityRules( acl ); - } - - /// - /// Processes the authentication data of a Windows Group - /// - /// - private void ReceivGroupIdentityRules( AuthorizationRuleCollection acl ) - { - Contract.Requires( acl != null ); - - // Only Handle Groups - if( WindowsIdentity.Groups == null ) - { - return; - } - - foreach( var identity in WindowsIdentity.Groups ) - { - for( var i = 0 ;i < acl.Count ;i++ ) - { - var rule = ( FileSystemAccessRule )acl[ i ]; - HandleFileSystemAccessRule( rule, identity ); - } - } - } - - /// - /// Processes the authentication data of a Windows identity - /// - /// FileSystemAccessRule - /// - private void HandleFileSystemAccessRule( FileSystemAccessRule rule, IdentityReference identity ) - { - Contract.Requires(rule != null); - Contract.Requires( identity != null ); - - if( rule == null ) - { - return; - } - - // Ignore all other users - if( identity.Equals( rule.IdentityReference ) ) - { - HandleAccessControlType( rule ); - } - } - - /// - /// Processes the authentication data of a Windows user - /// - /// - private void ReceiveUserIdentityRules( AuthorizationRuleCollection acl ) - { - Contract.Requires( acl != null ); - - if( WindowsIdentity.User == null ) - { - return; - } - - for( var i = 0 ;i < acl.Count ;i++ ) - { - var rule = ( FileSystemAccessRule )acl[ i ]; - HandleFileSystemAccessRule( rule, WindowsIdentity.User ); - } - } - - /// - /// Handles the access rights. Differentiates between allowed and denied rights - /// - private void HandleAccessControlType( FileSystemAccessRule rule ) - { - Contract.Requires( rule != null ); - - switch( rule.AccessControlType ) - { - case AccessControlType.Allow: - HandleAllowedAccessRule( rule ); - break; - case AccessControlType.Deny: - HandleDeniedAccessRule( rule ); - break; - } - } - - /// - /// Processed the permitted rights - /// - private void HandleAllowedAccessRule( FileSystemAccessRule rule ) - { - Contract.Requires( rule != null ); - - IsAllowedAppendData = Contains( FileSystemRights.AppendData, rule ); - IsAllowedChangePermissions = Contains( FileSystemRights.ChangePermissions, rule ); - IsAllowedCreateDirectories = Contains( FileSystemRights.CreateDirectories, rule ); - IsAllowedCreateFiles = Contains( FileSystemRights.CreateFiles, rule ); - IsAllowedDelete = Contains( FileSystemRights.Delete, rule ); - IsAllowedDeleteSubdirectoriesAndFiles = Contains( FileSystemRights.DeleteSubdirectoriesAndFiles, rule ); - IsAllowedExecuteFile = Contains( FileSystemRights.ExecuteFile, rule ); - IsAllowedFullControl = Contains( FileSystemRights.FullControl, rule ); - IsAllowedListDirectory = Contains( FileSystemRights.ListDirectory, rule ); - IsAllowedModify = Contains( FileSystemRights.Modify, rule ); - IsAllowedRead = Contains( FileSystemRights.Read, rule ); - IsAllowedReadAndExecute = Contains( FileSystemRights.ReadAndExecute, rule ); - IsAllowedReadAttributes = Contains( FileSystemRights.ReadAttributes, rule ); - IsAllowedReadData = Contains( FileSystemRights.ReadData, rule ); - IsAllowedReadExtendedAttributes = Contains( FileSystemRights.ReadExtendedAttributes, rule ); - IsAllowedReadPermissions = Contains( FileSystemRights.ReadPermissions, rule ); - IsAllowedSynchronize = Contains( FileSystemRights.Synchronize, rule ); - IsAllowedTakeOwnership = Contains( FileSystemRights.TakeOwnership, rule ); - IsAllowedTraverse = Contains( FileSystemRights.Traverse, rule ); - IsAllowedWrite = Contains( FileSystemRights.Write, rule ); - IsAllowedWriteAttributes = Contains( FileSystemRights.WriteAttributes, rule ); - IsAllowedWriteData = Contains( FileSystemRights.WriteData, rule ); - IsAllowedWriteExtendedAttributes = Contains( FileSystemRights.WriteExtendedAttributes, rule ); - } - - /// - /// Processed the denied rights - /// - private void HandleDeniedAccessRule( FileSystemAccessRule rule ) - { - Contract.Requires( rule != null ); - - IsDeniedAppendData = Contains( FileSystemRights.AppendData, rule ); - IsDeniedChangePermissions = Contains( FileSystemRights.ChangePermissions, rule ); - IsDeniedCreateDirectories = Contains( FileSystemRights.CreateDirectories, rule ); - IsDeniedCreateFiles = Contains( FileSystemRights.CreateFiles, rule ); - IsDeniedDelete = Contains( FileSystemRights.Delete, rule ); - IsDeniedDeleteSubdirectoriesAndFiles = Contains( FileSystemRights.DeleteSubdirectoriesAndFiles, rule ); - IsDeniedExecuteFile = Contains( FileSystemRights.ExecuteFile, rule ); - IsDeniedFullControl = Contains( FileSystemRights.FullControl, rule ); - IsDeniedListDirectory = Contains( FileSystemRights.ListDirectory, rule ); - IsDeniedModify = Contains( FileSystemRights.Modify, rule ); - IsDeniedRead = Contains( FileSystemRights.Read, rule ); - IsDeniedReadAndExecute = Contains( FileSystemRights.ReadAndExecute, rule ); - IsDeniedReadAttributes = Contains( FileSystemRights.ReadAttributes, rule ); - IsDeniedReadData = Contains( FileSystemRights.ReadData, rule ); - IsDeniedReadExtendedAttributes = Contains( FileSystemRights.ReadExtendedAttributes, rule ); - IsDeniedReadPermissions = Contains( FileSystemRights.ReadPermissions, rule ); - IsDeniedSynchronize = Contains( FileSystemRights.Synchronize, rule ); - IsDeniedTakeOwnership = Contains( FileSystemRights.TakeOwnership, rule ); - IsDeniedTraverse = Contains( FileSystemRights.Traverse, rule ); - IsDeniedWrite = Contains( FileSystemRights.Write, rule ); - IsDeniedWriteAttributes = Contains( FileSystemRights.WriteAttributes, rule ); - IsDeniedWriteData = Contains( FileSystemRights.WriteData, rule ); - IsDeniedWriteExtendedAttributes = Contains( FileSystemRights.WriteExtendedAttributes, rule ); - } - - - /// - /// Returs the if is in - /// - public Boolean Contains( FileSystemRights right, FileSystemAccessRule rule ) - { - Contract.Requires( rule != null ); - - return ( ( ( Int32 )right & ( Int32 )rule.FileSystemRights ) == ( Int32 )right ); - } - - /// - /// Get the File Information and set's the result to on success. - /// Also set's owner and owner's domain - /// - /// true on success. Use native win32 exception to get further error information - private void GetSecurityFromFileSystem() - { - IntPtr sidHandle = new IntPtr(); - try - { - this.FileSystemSecurityInformation = ReceiveFileSystemSecurityInformation( out sidHandle ); - } - finally - { - Win32SafeNativeMethods.LocalFree( sidHandle ); - } - } - - /// - /// Gets the security information of specified handle from file system - /// - /// Handle to get file security information - /// Result - private CommonObjectSecurity ReceiveFileSystemSecurityInformation( out IntPtr sidHandle ) - { - IntPtr zeroHandle = new IntPtr(); - IntPtr pSecurityDescriptor = new IntPtr(); - - try - { - var namedSecInfoResult = Win32SafeNativeMethods.GetNamedSecurityInfo( PathInfo.FullNameUnc, Win32SecurityObjectType.SeFileObject, - Win32FileSystemEntrySecurityInformation.OwnerSecurityInformation | Win32FileSystemEntrySecurityInformation.DaclSecurityInformation, - out sidHandle, out zeroHandle, out zeroHandle, out zeroHandle, out pSecurityDescriptor ); - var win32Error = Marshal.GetLastWin32Error(); - // Cancel if call failed - - if( namedSecInfoResult != 0 ) - { - Win32ErrorCodes.NativeExceptionMapping( PathInfo.FullName, win32Error ); - } - - var securityDescriptorLength = Win32SafeNativeMethods.GetSecurityDescriptorLength( pSecurityDescriptor ); - var securityDescriptorDataArray = new byte[ securityDescriptorLength ]; - Marshal.Copy( pSecurityDescriptor, securityDescriptorDataArray, 0, ( int )securityDescriptorLength ); - - CommonObjectSecurity securityInfo; - if( PathInfo.Attributes.Contains( FileAttributes.Directory ) ) - { - securityInfo = new DirectorySecurity(); - securityInfo.SetSecurityDescriptorBinaryForm( securityDescriptorDataArray ); - } - else - { - securityInfo = new FileSecurity(); - securityInfo.SetSecurityDescriptorBinaryForm( securityDescriptorDataArray ); - } - - return securityInfo; - } - finally - { - Win32SafeNativeMethods.LocalFree( zeroHandle ); - Win32SafeNativeMethods.LocalFree( pSecurityDescriptor ); - } - } - - - #endregion - - /// - /// File System Security Information - /// - public CommonObjectSecurity FileSystemSecurityInformation { get; private set; } - } - -} - diff --git a/src/SchwabenCode.QuickIO/QuickIOFolderStatisticResult.cs b/src/SchwabenCode.QuickIO/QuickIOFolderStatisticResult.cs deleted file mode 100644 index 700d602..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOFolderStatisticResult.cs +++ /dev/null @@ -1,44 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - /// - /// Folder Statistics - /// - public class QuickIOFolderStatisticResult - { - /// - /// Folder Count - /// - public ulong FolderCount { get; private set; } - - /// - /// File Count - /// - public ulong FileCount { get; private set; } - - /// - /// Total TotalBytes - /// - public ulong TotalBytes { get; private set; } - - /// - /// Creates new Instance of - internal access only - /// - /// Folder Count - /// File Count - /// Total TotalBytes - internal QuickIOFolderStatisticResult( UInt64 folderCount, UInt64 fileCount, UInt64 size ) - { - FolderCount = folderCount; - FileCount = fileCount; - TotalBytes = size; - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/QuickIOHash.cs b/src/SchwabenCode.QuickIO/QuickIOHash.cs deleted file mode 100644 index 659c09d..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOHash.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.Security.Cryptography; -using System.Text; - -namespace SchwabenCode.QuickIO -{ - /// - /// Hashing and Encryption - /// - public static class QuickIOHash - { - /// - /// File chunk hash calculation - /// - public static QuickIOHashResult Calculate( HashAlgorithm algorithm, string content, Encoding encoding = null ) - { - Contract.Requires( algorithm != null ); - Contract.Requires( !String.IsNullOrEmpty( content ) ); - Contract.Ensures( Contract.Result() != null ); - - encoding = encoding ?? Encoding.UTF8; - return Calculate( algorithm, encoding.GetBytes( content ) ); - } - - /// - /// File chunk hash calculation - /// - public static QuickIOHashResult Calculate( HashAlgorithm algorithm, byte[ ] bytes ) - { - Contract.Requires( algorithm != null ); - Contract.Requires( bytes != null ); - Contract.Ensures( Contract.Result() != null ); - - return new QuickIOHashResult( algorithm.ComputeHash( bytes ) ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOHashResult.cs b/src/SchwabenCode.QuickIO/QuickIOHashResult.cs deleted file mode 100644 index c67089a..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOHashResult.cs +++ /dev/null @@ -1,121 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.Text; -using System.Threading; - -namespace SchwabenCode.QuickIO -{ - /// - /// This class is used for hash calculations. - /// Use - /// Format - /// - /// for human readable output. - /// - /// - /// - /// // Show human readable hash - /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" ); - /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8, "x2" ); - /// - /// - public class QuickIOHashResult - { - private readonly byte[ ] _hashBytes; - - /// - /// The bytes that represents the calculation result - /// - public byte[ ] HashBytes - { - get - { - Contract.Ensures( Contract.Result() != null ); - return _hashBytes; - } - } - - /// - /// Creates an instance of - /// - /// - internal QuickIOHashResult( byte[ ] hashBytes ) - { - Contract.Requires( hashBytes != null ); - _hashBytes = hashBytes; - } - - /// - /// Formats the as a hexadecimal string using UTF8 encoding. - /// - /// Formated string - /// - /// - /// // Show human readable hash - /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" ); - /// Console.WriteLine("Hash: {0}", hashResult.Format( ); - /// - /// - public string Format() - { - Contract.Ensures( Contract.Result() != null ); - return Format( Encoding.UTF8 ); - } - - /// - /// Formats the as a hexadecimal string using specified encoding. - /// - /// Encoding for formatting - /// Formated string - /// - /// - /// // Show human readable hash - /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" ); - /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8 ); - /// - /// - public string Format( Encoding encoding ) - { - Contract.Requires( encoding != null ); - Contract.Ensures( Contract.Result() != null ); - - return Format( encoding, "x2" ); - } - - /// - /// Formats the using specified encoding and format. - /// - /// Encoding for formatting - /// Pattern for formatting. Use x2 for hexadecimal output. - /// Cancel token - /// Formated string - /// - /// - /// // Show human readable hash - /// QuickIOHashResult hashResult = QuickIOFile.CalculateSha256Hash( "C:\temp\image.bin" ); - /// Console.WriteLine("Hash: {0}", hashResult.Format( Encoding.UTF8, "x2" ); - /// - /// - public string Format( Encoding encoding, String format, CancellationToken cancellationToken = default( CancellationToken ) ) - { - Contract.Requires( encoding != null ); - Contract.Requires( !String.IsNullOrWhiteSpace( format ) ); - Contract.Ensures( Contract.Result() != null ); - - StringBuilder sb = new StringBuilder(); - foreach (byte t in HashBytes) - { - cancellationToken.ThrowIfCancellationRequested(); - - sb.Append( t.ToString( format ) ); - } - - return sb.ToString(); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOPath.Constants.cs b/src/SchwabenCode.QuickIO/QuickIOPath.Constants.cs deleted file mode 100644 index 3a6743d..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOPath.Constants.cs +++ /dev/null @@ -1,78 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; - -namespace SchwabenCode.QuickIO -{ - /// - /// Performs operations for files or directories and path information. - /// - public static partial class QuickIOPath - { - /// - /// Maximum allowed length of a regular path - /// - public const Int32 MaxRegularPathLength = 260; - - /// - /// Max allowed path element name like folder names or file names - /// - public const int MaxPathElementLength = 255; - - /// - /// Max allowed length of folder name - /// - public const int MaxFolderNameLength = MaxPathElementLength; - /// - /// Max allowed length of file name - /// - public const int MaxFileNameLength = MaxPathElementLength; - - /// - /// Maximum allowed length of a regular folder path - /// - public const Int32 MaxSimpleDirectoryPathLength = 247; - - /// - /// Maximum allowed length of an UNC Path - /// - public const Int32 MaxUncPathLength = 32767; - - /// - /// Regular local path prefix - /// - public const String RegularLocalPathPrefix = @""; - - /// - /// Path prefix for shares - /// - public const String RegularSharePathPrefix = @"\\"; - - /// - /// Length of Path prefix for shares - /// - public static readonly Int32 RegularSharePathPrefixLength = RegularSharePathPrefix.Length; - - /// - /// UNC prefix for regular paths - /// - public const String UncLocalPathPrefix = @"\\?\"; - - /// - /// UNC prefix for shares - /// - public const String UncSharePathPrefix = @"\\?\UNC\"; - - /// - /// Directory Separator Char - /// - public static char DirectorySeparatorChar = System.IO.Path.DirectorySeparatorChar; - /// - /// WhiteSpace = ' ' - /// - public static char WhiteSpace = ' '; - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOPath.Exists.cs b/src/SchwabenCode.QuickIO/QuickIOPath.Exists.cs deleted file mode 100644 index 3a0d215..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOPath.Exists.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIOPath - { - /// - /// Checks if path exists - /// - /// Path to check - /// True on exists - public static Boolean Exists( String path ) - { - return QuickIOEngine.Exists( path ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOPath.Get.cs b/src/SchwabenCode.QuickIO/QuickIOPath.Get.cs deleted file mode 100644 index 83a196d..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOPath.Get.cs +++ /dev/null @@ -1,228 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Runtime.CompilerServices; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIOPath - { - /// - /// Returns - /// - /// - public static String GetRandomFileName() - { - Contract.Ensures( !String.IsNullOrWhiteSpace( Contract.Result() ) ); - return System.IO.Path.GetRandomFileName(); - } - - /// - /// Gets name of file or directory - /// - /// Path - /// Name of file or directory - /// Path is invalid - public static String GetName( String fullName ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( fullName ) ); - Contract.Ensures( !String.IsNullOrWhiteSpace( Contract.Result() ) ); - - string path = InternalTrimTrailingSeparator( fullName ); - int pos = path.LastIndexOf( DirectorySeparatorChar ); - - return ( ( pos == -1 ) ? path : path.Substring( pos + 1 ) ); - } - - /// - /// A wrapper for - /// - /// Calls - /// a regular path - public static String GetFullPath( String path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( !String.IsNullOrWhiteSpace( Contract.Result() ) ); - - // Only access System.IO on relative path - if( IsRelative( path ) ) - { - return System.IO.Path.GetFullPath( path ); - } - - // otherwise it is a valid path - return path; - - } - - /// - /// A wrapper for that returns - /// - public static QuickIOPathInfo GetFullPathInfo( String path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( Contract.Result() != null ); - - return new QuickIOPathInfo( GetFullPath( path ) ); - } - - /// - /// Full path, no relative path allowed - /// - /// Same return behavior like - /// Null if is null, empty string if does not contain any root information or is invalid. - public static string GetPathRoot( string path ) - { - // The System.IO behavior is to return null on null - if( path == null ) - { - return null; - } - - // Return C:\ - string root; - if( TryGetLocalRootPath( path, out root ) ) - { - return root; - } - - - // Return \\server\name - if( TryGetShareRootPath( path, out root ) ) - { - return root; - } - - // Return \\?\UNC\C:\ - if( TryGetLocalUncRootPath( path, out root ) ) - { - return root; - } - - // Return \\?\UNC\server\share - if( TryGetShareUncRootPath( path, out root ) ) - { - return root; - } - - // The System.IO behavior is to return "" on invalid path - return ""; - } - - /// - /// Returns true if can be parsed and puts root information to - /// - internal static bool TryGetLocalRootPath( string path, out string root ) - { - if( IsLocalRegular( path ) ) - { - root = path.Substring( 0, 3 ); - return true; - } - - root = null; - return false; - } - - /// - /// Returns true if can be parsed and puts root information to - /// - internal static bool TryGetLocalUncRootPath( string path, out string root ) - { - if( IsLocalUnc( path ) ) - { - root = path.Substring( 0, 7 ); - return true; - } - - root = null; - return false; - } - - /// - /// Returns true if can be parsed and puts root information to - /// - internal static bool TryGetShareRootPath( string path, out string root ) - { - string serverName; - string shareName; - if( IsShareRegular( path ) && TryParseShare( path, QuickIOPathType.Regular, out serverName, out shareName ) ) - { - root = $@"{RegularSharePathPrefix}{serverName}\{shareName}"; - return true; - } - - root = null; - return false; - } - - /// - /// Returns true if can be parsed and puts root information to - /// - internal static bool TryGetShareUncRootPath( string path, out string root ) - { - string serverName; - string shareName; - if( IsShareUnc( path ) && TryParseShare( path, QuickIOPathType.UNC, out serverName, out shareName ) ) - { - root = $@"{UncSharePathPrefix}{serverName}\{shareName}"; - return true; - } - - root = null; - return false; - } - - /// - /// Strips server and share from given path - /// - /// Returns false if path is invalid for this operation - [MethodImpl( 256 )] - internal static Boolean TryParseShare( string path, QuickIOPathType shouldBe, out string serverName, out string shareName ) - { - string[ ] pathElements; - return TryParseShare( path, shouldBe, out serverName, out shareName, out pathElements ); - } - - /// - /// Strips server and share from given path - /// - /// Returns false if path is invalid for this operation - [MethodImpl( 256 )] - internal static Boolean TryParseShare( string path, QuickIOPathType shouldBe, out string serverName, out string shareName, out string[ ] pathElements ) - { - serverName = null; - shareName = null; - pathElements = null; - - // Validate input - if( String.IsNullOrWhiteSpace( path ) ) - { - return false; - } - - if( shouldBe == QuickIOPathType.UNC ) - { - path = path.Substring( QuickIOPath.UncSharePathPrefix.Length ); - } - - // try to found server and name - string[ ] names = path.Trim( '\\' /*trim start and end */ ).Split( '\\' ); - if( names.Length < 2 ) - { - // if less than two it is invalid - return false; - } - - serverName = names[ 0 ]; - shareName = names[ 1 ]; - pathElements = names.Skip( 2 ).ToArray(); - return true; - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOPath.IsPath.cs b/src/SchwabenCode.QuickIO/QuickIOPath.IsPath.cs deleted file mode 100644 index a8044f2..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOPath.IsPath.cs +++ /dev/null @@ -1,198 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.Runtime.CompilerServices; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIOPath - { - /// - /// Checks if given path starts with a known root path - /// - [MethodImpl( 256 )] - public static Boolean IsRelative( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - // If IsPath then it is no relative path - return !IsPath( path ); - } - - /// - /// Returns true if given path is or - /// - /// Will return true on C:\ but will return false on C:\folderName - [MethodImpl( 256 )] - public static bool IsPath( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - // Local checks - return ( IsLocal( path ) || IsShare( path ) ); - } - - /// - /// Checks if given path matches C:\ or X:\ ... - /// - [MethodImpl( 256 )] - public static Boolean IsLocal( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - // compare to regular and unc - return ( IsLocalRegular( path ) || IsLocalUnc( path ) ); - } - - /// - /// Checks if given path matches C:\ or X:\ ... - /// - [MethodImpl( 256 )] - public static Boolean IsShare( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - // compare to regular and unc - return ( IsShareRegular( path ) || IsShareUnc( path ) ); - } - - /// - /// Checks if given path matches C:\ or X:\ ... - /// - [MethodImpl( 256 )] - public static Boolean IsLocalRegular( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - // Validate input - if( String.IsNullOrWhiteSpace( path ) ) - { - return false; - } - - return ( ( path.Length >= 3 ) && IsRootLocalRegular( path.Substring( 0, 3 ) ) ); - } - - /// - /// Checks if given path matches \\?\C:\ or \\?\X:\ ... - /// - [MethodImpl( 256 )] - public static Boolean IsLocalUnc( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - // Validate input - if( String.IsNullOrWhiteSpace( path ) ) - { - return false; - } - - return ( ( path.Length >= 7 ) && IsRootLocalUnc( path.Substring( 0, 7 ) ) ); - } - - /// - /// Checks if given path matches \\s\s - /// - [MethodImpl( 256 )] - public static Boolean IsShareRegular( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - // check if path exists and starts with \\ - if( String.IsNullOrWhiteSpace( path ) || !path.StartsWith( RegularLocalPathPrefix ) ) - { - return false; - } - - // filter unc paths - if( InternalStartsWithExpected( path, UncLocalPathPrefix ) || InternalStartsWithExpected( path, UncSharePathPrefix ) ) - { - return false; - } - - const string expectedPrefix = QuickIOPath.RegularSharePathPrefix; - if( !InternalStartsWithExpected( path, expectedPrefix ) ) - { - return false; - } - - var location = path.Substring( expectedPrefix.Length ); - - // strip information - string serverName; - string shareName; - if( !TryParseShare( location, QuickIOPathType.Regular, out serverName, out shareName ) ) - { - return false; - } - - // validate - return IsValidServerName( serverName ) && IsValidShareName( shareName ); - } - - /// - /// True if starts with or - /// - [MethodImpl( 256 )] - public static bool IsUnc( string path ) - { - return ( IsShareUnc( path ) || IsLocalUnc( path ) ); - } - - /// - /// Checks if given path matches \\?\UNC\server\name - /// - /// Min length: \\?\UNC\s\s - [MethodImpl( 256 )] - public static Boolean IsShareUnc( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - // Validate input - if( String.IsNullOrWhiteSpace( path ) ) - { - return false; - } - - const string expectedPrefix = QuickIOPath.UncSharePathPrefix; - if( !InternalStartsWithExpected( path, expectedPrefix ) || expectedPrefix == path ) - { - return false; - } - - // strip information - string serverName; - string shareName; - if( !TryParseShare( path, QuickIOPathType.UNC, out serverName, out shareName ) ) - { - return false; - } - - // validate - return IsValidServerName( serverName ) && IsValidShareName( shareName ); - } - - - - /// - /// Checks if given path starts with expected prefix and has min length - /// - /// Internal = no validation - [MethodImpl( 256 )] - internal static Boolean InternalStartsWithExpected( string path, String prefix ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( prefix ) ); - - return - // check length - ( path.Length >= prefix.Length ) - // check prefix - && ( path.Substring( 0, prefix.Length ).Equals( prefix, StringComparison.OrdinalIgnoreCase ) ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOPath.IsRoot.cs b/src/SchwabenCode.QuickIO/QuickIOPath.IsRoot.cs deleted file mode 100644 index 2e4d02e..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOPath.IsRoot.cs +++ /dev/null @@ -1,170 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Runtime.CompilerServices; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIOPath - { - /// - /// Returns true if given path is or - /// - /// Will return true on C:\ but will return false on C:\folderName - [MethodImpl( 256 )] - public static bool IsRoot( string path ) - { - // Local checks - return ( IsRootLocal( path ) || IsRootShare( path ) ); - } - - /// - /// Checks if given path is local root - /// - [MethodImpl( 256 )] - public static bool IsRootLocal( string path ) - { - return ( IsRootLocalRegular( path ) || IsRootLocalUnc( path ) ); - } - - /// - /// Checks if given path is share root - /// - [MethodImpl( 256 )] - public static bool IsRootShare( string path ) - { - return ( IsRootShareRegular( path ) || IsRootShareUnc( path ) ); - } - - /// - /// Checks if given path matches C:\ or X:\ ... - /// - [MethodImpl( 256 )] - public static bool IsRootLocalRegular( string path ) - { - // Validate input - if( string.IsNullOrWhiteSpace( path ) ) - { - return false; - } - - return - // check length - ( path.Length == 3 - // check root - && ( ( IsValidDriveLetter( path[ 0 ] ) && path[ 1 ] == ':' && path[ 2 ] == '\\' ) ) ); - } - - /// - /// Checks if given path matches \\?\C:\ or \\?\X:\ ... - /// - [MethodImpl( 256 )] - public static bool IsRootLocalUnc( string path ) - { - // Validate input - if( string.IsNullOrWhiteSpace( path ) ) - { - return false; - } - - return - // check length - ( ( path.Length == 7 ) - // check prefix - && InternalStartsWithExpected( path, UncLocalPathPrefix ) - // check root - && IsRootLocalRegular( path.Substring( 4, 3 ) ) ); - } - - /// - /// Checks if given path matches \\server\name - /// - /// Min length: \\s\s - [MethodImpl( 256 )] - public static Boolean IsRootShareRegular( string path ) - { - // Validate input - if( String.IsNullOrWhiteSpace( path ) ) - { - return false; - } - - // check prefix - const string expectedPrefix = RegularSharePathPrefix; - if( !InternalStartsWithExpected( path, expectedPrefix ) ) - { - return false; - } - - string location = path.Substring( expectedPrefix.Length ); - // first char if location must be alphnum - if( !char.IsLetterOrDigit( location[ 0 ] ) ) - { - return false; - } - - // try to found server and name - // only two parts are valid here! - string[ ] names = location.TrimEnd( '\\' ).Split( '\\' ); - if( names.Length != 2 ) - { - // if less than two it is invalid - return false; - } - - string serverName = names[ 0 ]; - string shareName = names[ 1 ]; - - // TODO: validate server and share names here - - return IsValidServerName( serverName ) && IsValidShareName( shareName ); - } - - /// - /// Checks if given path matches \\?\UNC\server\name - /// - /// Min length: \\?\UNC\s\s - [MethodImpl( 256 )] - public static bool IsRootShareUnc( string path ) - { - // Validate input - if( String.IsNullOrWhiteSpace( path ) ) - { - return false; - } - - const string expectedPrefix = QuickIOPath.UncSharePathPrefix; - if( !InternalStartsWithExpected( path, expectedPrefix ) ) - { - return false; - } - - // strip information - string serverName; - string shareName; - string[ ] pathElements; - if( !TryParseShare( path, QuickIOPathType.UNC, out serverName, out shareName, out pathElements ) ) - { - return false; - } - - // check location - // if location is present it is no root - if( pathElements != null && pathElements.Length > 0 ) - { - return false; - } - - // validate - return IsValidServerName( serverName ) && IsValidShareName( shareName ); - } - - - - - - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOPath.IsValid.cs b/src/SchwabenCode.QuickIO/QuickIOPath.IsValid.cs deleted file mode 100644 index 03b7fe3..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOPath.IsValid.cs +++ /dev/null @@ -1,144 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Runtime.CompilerServices; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIOPath - { - /// - /// Checks if given name is a valid server name - /// - /// Ignores Unix File Systems - /// Name to check - /// If invalid character found - [MethodImpl( 256 )] - public static bool IsValidFolderName( String name ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( name ) ); - - // check system names - - if( String.IsNullOrWhiteSpace( name ) || name == "." || name == ".." ) - { - return false; - } - - // whitespace and the start or end not allowed - if( name[ 0 ] == WhiteSpace || name[ name.Length - 1 ] == WhiteSpace ) - { - return false; - } - - // max length - if( name.Length > QuickIOPath.MaxFolderNameLength ) - { - return false; - } - - // point at the beginning or at the end is not allowed - // windows would automatically remove the point at the end - if( name[ 0 ] == '.' || name[ name.Length - 1 ] == '.' ) - { - return false; - } - - return name.All( IsValidFolderChar ); - } - - /// - /// returns true if char is invalid for a folder name - /// - /// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#naming_conventions - [MethodImpl( 256 )] - public static Boolean IsValidFolderChar( char c ) - { - // TODO: think about whitelisting instead of blacklisting - const string forbiddenChars = "<>:\"/\\|?*\0"; - - // Whitespaces are allowed - if( c == WhiteSpace ) - { - return true; - } - - // but all others chars below ascii 32 are forbidden - if( c < 32 ) - { - return false; - } - - // at least some chars are forbidden - return ( forbiddenChars.IndexOf( c ) == -1 ); - } - - /// - /// Checks if given char is a valid windows drive letter - /// - [MethodImpl( 256 )] - public static bool IsValidDriveLetter( char c ) - { - // hint: older versions of windows were able to allow [:\ but current systems won't! - return ( ( c >= 'A' && c <= 'Z' ) || ( c >= 'a' && c <= 'z' ) ); - } - - /// - /// Verifies server name - /// - [MethodImpl( 256 )] - public static bool IsValidServerName( string serverName ) - { - if( String.IsNullOrWhiteSpace( serverName ) ) - { - return false; - } - - // TODO: check rule set - return serverName.All( IsValidServerNameChar ); - } - - /// - /// returns true if char is valid for a server name - /// - [MethodImpl( 256 )] - public static bool IsValidServerNameChar( char c ) - { - // TODO: constant - // TODO: are these all? https://technet.microsoft.com/en-us/library/cc959336.aspx - const string allowedChars = "-"; - return ( Char.IsLetterOrDigit( c ) || ( allowedChars.IndexOf( c ) > -1 ) ); - } - - /// - /// Returns true if share name is valid - /// - [MethodImpl( 256 )] - public static bool IsValidShareName( string serverName ) - { - if( String.IsNullOrWhiteSpace( serverName ) ) - { - return false; - } - - // TODO: check rule set - return serverName.All( IsValidShareNameChar ); - } - - /// - /// Returns true if char is valid for a share name - /// - [MethodImpl( 256 )] - public static bool IsValidShareNameChar( char c ) - { - // TODO: constant - const string allowedChars = "_- ."; - return ( Char.IsLetterOrDigit( c ) || ( allowedChars.IndexOf( c ) > -1 ) ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOPath.ToPath.cs b/src/SchwabenCode.QuickIO/QuickIOPath.ToPath.cs deleted file mode 100644 index 0435d75..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOPath.ToPath.cs +++ /dev/null @@ -1,136 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIOPath - { - /// - /// Converts unc path to regular path - /// - /// If path is invalid or cannot be identified - public static String ToPathRegular( String path ) - { - Contract.Requires( !String.IsNullOrEmpty( path ) ); - Contract.Ensures( !String.IsNullOrEmpty( Contract.Result() ) ); - - - // convert to share - if( IsShareUnc( path ) ) - { - return QuickIOPath.ToSharePathRegular( path ); - } - // convert to local - if( IsLocalUnc( path ) ) - { - return QuickIOPath.ToLocalPathRegular( path ); - } - - // give origin if already regular - if( IsShareRegular( path ) || IsLocalRegular( path ) ) - { - // already regular - return path; - } - - - // it is already a regular path - // or invalid. but will not be checked here - return path; - } - - /// - /// Converts regular path to unc path - /// - /// If path is invalid or cannot be identified - public static string ToPathUnc( string path ) - { - Contract.Requires( !String.IsNullOrEmpty( path ) ); - - // give origin if already unc - if( IsShareUnc( path ) || IsLocalUnc( path ) ) - { - // already unc - return path; - } - - // convert to share - if( IsShareRegular( path ) ) - { - return QuickIOPath.ToSharePathUnc( path ); - } - // convert to local - if( IsLocalRegular( path ) ) - { - return QuickIOPath.ToLocalPathUnc( path ); - } - - // it is already a regular path - // or invalid. but will not be checked here - return path; - } - - ///// - ///// Formats a path - ///// - ///// Target format type - ///// Path to format - ///// Formatted path - //internal static string InternalFormatPathByType( QuickIOPathType pathFormatReturn, string uncPath ) - //{ - // Contract.Requires( !String.IsNullOrWhiteSpace( uncPath ) ); - // Contract.Ensures( Contract.Result() != null ); - - // return pathFormatReturn == QuickIOPathType.Regular ? ToPathRegular( uncPath ) : uncPath; - //} - - /// - /// Converts an unc path to a local regular path - /// - /// Unc Path - /// \\?\C:\temp\file.txt >> C:\temp\file.txt - /// Local Regular Path - public static String ToLocalPathRegular( String uncLocalPath ) - { - return uncLocalPath.Substring( UncLocalPathPrefix.Length ); - } - - /// - /// Converts an unc path to a share regular path - /// - /// Unc Path - /// \\?\UNC\server\share >> \\server\share - /// QuickIOShareInfo Regular Path - public static String ToSharePathRegular( String uncSharePath ) - { - return RegularSharePathPrefix + uncSharePath.Substring( UncSharePathPrefix.Length ); - } - - /// - /// Converts a regular local path to an unc path - /// - /// Regular Path - /// C:\temp\file.txt >> \\?\C:\temp\file.txt - /// Local Unc Path - public static String ToLocalPathUnc( String regularLocalPath ) - { - return UncLocalPathPrefix + regularLocalPath; - } - - /// - /// Converts a regular share path to an unc path - /// - /// Regular Path - /// \\server\share\file.txt >> \\?\UNC\server\share\file.txt - /// QuickIOShareInfo Unc Path - public static String ToSharePathUnc( String regularSharePath ) - { - return UncSharePathPrefix + regularSharePath.Substring( RegularSharePathPrefix.Length ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOPath.cs b/src/SchwabenCode.QuickIO/QuickIOPath.cs deleted file mode 100644 index e4770d7..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOPath.cs +++ /dev/null @@ -1,109 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.Runtime.CompilerServices; - -namespace SchwabenCode.QuickIO -{ - /// - /// Performs operations for files or directories and path information. - /// - public static partial class QuickIOPath - { - /// - /// Removes spaces end at the end of a string - /// - internal static String InternalTrimTrailingSeparator( String path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - Contract.Ensures( !String.IsNullOrWhiteSpace( Contract.Result() ) ); - - return path.TrimEnd( WhiteSpace ).TrimEnd( DirectorySeparatorChar ); - } - - - - /// - /// Combines given path elements - /// - /// Path elements to combine - /// Combined Path - /// No validation - public static String Combine( params String[ ] pathElements ) - { - Contract.Requires( pathElements != null ); - Contract.Requires( pathElements.Length > 0 ); - Contract.Ensures( !String.IsNullOrWhiteSpace( Contract.Result() ) ); - - if( pathElements == null || pathElements.Length == 0 ) - { - throw new ArgumentNullException( nameof( pathElements ), "Cannot be null or empty" ); - } - - // Verify not required; System.IO.Path.Combine calls internal path invalid char verifier - - // First Element - string combinedPath = pathElements[ 0 ]; - - // Other elements - for( int i = 1 ;i < pathElements.Length ;i++ ) - { - string el = pathElements[ i ]; - - // Combine - combinedPath = System.IO.Path.Combine( combinedPath, el ); - } - - return combinedPath; - } - - /// - /// Returns the parent directory path - /// - /// Path to get the parent - /// System.IO does not support relative paths here. QuickIO does. - /// Parent directory or null if parent is root - public static String GetDirectoryName( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - if( String.IsNullOrWhiteSpace( path ) ) - { - return null; - } - - // do here just trim spaces - string cleanPath = path.Trim(); - - if( IsRoot( cleanPath ) ) - { - return null; - } - - // trim again spaces and slashes - cleanPath = Clean( path ); - - int lastDirectorySeparatorChar = cleanPath.LastIndexOf( DirectorySeparatorChar ); - if( lastDirectorySeparatorChar == -1 ) - { - return null; - } - return cleanPath.Substring( 0, lastDirectorySeparatorChar ); - - } - - - /// - /// Removes all spaces and trims backslahes at the end. - /// - /// returns null if is null. - public static string Clean( string path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - return path?.Trim().Trim( '\\' ).Trim(); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOPathInfo.cs b/src/SchwabenCode.QuickIO/QuickIOPathInfo.cs deleted file mode 100644 index 95f6577..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOPathInfo.cs +++ /dev/null @@ -1,229 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - - -using System; -using System.Diagnostics.Contracts; -using System.IO; -using System.Security.Principal; -using SchwabenCode.QuickIO.Engine; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - /// - /// Provides properties and instance method for paths - /// - public sealed class QuickIOPathInfo - { - /// - /// Creates the path information container - /// - /// Full path to the file or directory (regular or unc) - internal QuickIOPathInfo( String fullpath ) : - this( fullpath, QuickIOEngine.GetFindDataFromPath( fullpath ) ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( fullpath ) ); - } - - /// - /// Creates the path information container - /// - /// Full path to the file or directory (regular or unc) - /// Win32 handle information - internal QuickIOPathInfo( string fullpath, Win32FindData win32FindData ) - { - Contract.Requires( fullpath != null ); - //Changed to allow paths which do not exist: - //Contract.Requires( win32FindData != null ); - - this.FindData = win32FindData; - - - this.Name = QuickIOPath.GetName( fullpath ); - this.FullName = QuickIOPath.ToPathRegular( fullpath ); - this.FullNameUnc = QuickIOPath.ToPathUnc( fullpath ); - - // TODO: - this.Parent = QuickIOPath.GetDirectoryName( fullpath ); - this.Root = QuickIOPath.GetPathRoot( fullpath ); - - this.IsRoot = QuickIOPath.IsRoot( fullpath ); - } - - - //public String GetFullname( QuickIOPathType formatReturn = QuickIOPathType.Regular ) - //{ - // Contract.Ensures( !String.IsNullOrWhiteSpace( Contract.Result() ) ); - - // if( formatReturn == QuickIOPathType.Regular ) - // { - // return Path; - // } - // return FullNameUnc; - //} - - /// - /// Path to file or directory (regular format) - /// - public String FullName { get; } - - /// - /// Path to file or directory (unc format) - /// - public String FullNameUnc { get; } - - /// - /// Name of file or directory - /// - public String Name { get; private set; } - - /// - /// Parent Directory - /// - public string Parent { get; } - - /// - /// FindData - /// - internal Win32FindData FindData - { - get - { - if( IsRoot ) - { - throw new NotSupportedException( "Root directory does not provide owner access" ); - } - return _findData ?? ( _findData = QuickIOEngine.GetFindDataFromPath( FullNameUnc ) ); - } - private set - { - _findData = value; - } - } - private Win32FindData _findData; - - /// - /// Attributes. Cached. - /// - /// if path is root - public FileAttributes Attributes - { - get - { - if( IsRoot ) - { - throw new NotSupportedException( "Root directory does not provide attributes" ); - } - return FindData.dwFileAttributes; - } - internal set { FindData.dwFileAttributes = value; } - } - - /// - /// Returns true if current path is root - /// - public bool IsRoot { get; } - - /// - /// Returns Root or null if current path is root - /// - public string Root { get; } - - /// - /// Returns true if path exists. Checks - /// - /// - public Boolean Exists - { - get - { - Contract.Requires( !String.IsNullOrWhiteSpace( FullNameUnc ) ); - return QuickIOEngine.Exists( FullNameUnc ); - } - } - - /// - /// Returns true if path exists. Checks against the file system - /// - public QuickIOFileSystemEntryType SystemEntryType - { - get - { - Contract.Requires( FullNameUnc != null ); - return QuickIOEngine.DetermineFileSystemEntry( FullNameUnc ); - } - - } - - /// - /// Returns current - /// - /// - public QuickIOFileSystemSecurity GetFileSystemSecurity() - { - Contract.Ensures( Contract.Result() != null ); - return new QuickIOFileSystemSecurity( this ); - } - - /// - /// Determines the owner - /// - /// - public NTAccount GetOwner() - { - Contract.Ensures( Contract.Result() != null ); - - if( IsRoot ) - { - throw new NotSupportedException( "Root directory does not provide owner access" ); - } - return GetOwnerIdentifier().Translate( typeof( NTAccount ) ) as NTAccount; - } - - /// - /// Determines the owner - /// - /// - public IdentityReference GetOwnerIdentifier() - { - Contract.Ensures( Contract.Result() != null ); - - if( IsRoot ) - { - throw new NotSupportedException( "Root directory does not provide owner access" ); - } - return GetFileSystemSecurity().FileSystemSecurityInformation.GetOwner( typeof( SecurityIdentifier ) ); - } - - /// - /// Sets the owner - /// - public void SetOwner( NTAccount newOwner ) - { - Contract.Requires( newOwner != null ); - - if( IsRoot ) - { - throw new NotSupportedException( "Root directory does not provide owner access" ); - } - GetFileSystemSecurity().FileSystemSecurityInformation.SetOwner( newOwner.Translate( typeof( SecurityIdentifier ) ) ); - } - - /// - /// Sets the owner - /// - public void SetOwner( IdentityReference newOwersIdentityReference ) - { - Contract.Requires( newOwersIdentityReference != null ); - - if( IsRoot ) - { - throw new NotSupportedException( "Root directory does not provide owner access" ); - } - GetFileSystemSecurity().FileSystemSecurityInformation.SetOwner( newOwersIdentityReference ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOPatterns.cs b/src/SchwabenCode.QuickIO/QuickIOPatterns.cs deleted file mode 100644 index 00deb06..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOPatterns.cs +++ /dev/null @@ -1,20 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; - -namespace SchwabenCode.QuickIO -{ - /// - /// Pattern Collection - /// - public static class QuickIOPatterns - { - /// - /// Matches all. No filtering. - /// - public const String PathMatchAll = "*"; - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/QuickIORecommendedValues.cs b/src/SchwabenCode.QuickIO/QuickIORecommendedValues.cs deleted file mode 100644 index 43e819f..0000000 --- a/src/SchwabenCode.QuickIO/QuickIORecommendedValues.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; - -namespace SchwabenCode.QuickIO -{ - /// - /// Various default and recommended values for different operations, connections and API calls - /// - public static class QuickIORecommendedValues - { - /// - /// Recommended buffer byte size for default read operations - /// - public const Int32 DefaultReadBufferBytes = 4096; - - /// - /// Recommended size of Byte packages for TCP connections - /// - public const Int32 TCPMaxPackageBytes = 65535; - - /// - /// Recommended size of Byte packages for local ethernet connections - /// - public const Int32 MTUMaxPackageBytes = 1500; - - /// - /// Recommended size of Byte packages for SMB connections - /// - /// See http://support.microsoft.com/kb/223140 - public const Int32 SMBMaxPackageBytes = 60 * 1024; - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOShare.Enumerate.cs b/src/SchwabenCode.QuickIO/QuickIOShare.Enumerate.cs deleted file mode 100644 index 1580644..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOShare.Enumerate.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using SchwabenCode.QuickIO.Win32; -using System.Diagnostics.Contracts; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - public static partial class QuickIOShare - { - /// - /// Enumerate shares of specific machine. If no machine is specified, local machine is used - /// - /// Collection of - public static IEnumerable EnumerateShares( String machineName = null, QuickIOShareApiReadLevel level = QuickIOShareApiReadLevel.Admin ) - { - Contract.Ensures( Contract.Result>() != null ); - - Type shareType = ( level == QuickIOShareApiReadLevel.Admin ) ? typeof( Win32ApiShareInfoAdmin ) : typeof( Win32ApiShareInfoNormal ); - switch( level ) - { - case QuickIOShareApiReadLevel.Admin: - return QuickIOEngine.EnumerateShares( QuickIOShareApiReadLevel.Admin, machineName ); - case QuickIOShareApiReadLevel.Normal: - return QuickIOEngine.EnumerateShares( QuickIOShareApiReadLevel.Normal, machineName ); - default: - throw new NotSupportedException( $"Unsupported level '{level}'" ); - } - } - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOShare.cs b/src/SchwabenCode.QuickIO/QuickIOShare.cs deleted file mode 100644 index 8b7caa2..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOShare.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - /// - /// Provides static methods to access network shares. - /// - public static partial class QuickIOShare - { - /// - /// Receives of specifies share path - /// - /// - /// See http://support.microsoft.com/kb/231497 - public static QuickIODiskInformation GetDiskInformation( String sharePath ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( sharePath ) ); - Contract.Ensures( Contract.Result() != null ); - - return QuickIOEngine.GetDiskInformation( sharePath ); - } - - } -} diff --git a/src/SchwabenCode.QuickIO/QuickIOShareInfo.DiskInformation.cs b/src/SchwabenCode.QuickIO/QuickIOShareInfo.DiskInformation.cs deleted file mode 100644 index 2738ef2..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOShareInfo.DiskInformation.cs +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIOShareInfo - { - /// - /// Returns of this instance. - /// - /// - /// Only supported for - /// Metadata not supported for this Sharetype. Only available for - public QuickIODiskInformation GetDiskInformation() - { - Contract.Requires( !String.IsNullOrWhiteSpace( FullName ) ); - Contract.Ensures( Contract.Result() != null ); - - if( this.ShareType != QuickIOShareType.Disk ) - { - throw new UnsupportedShareTypeException( "Metadata not supported for this Sharetype", this.FullName ); - } - - return QuickIOEngine.GetDiskInformation( this.FullName ); - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/QuickIOShareInfo.Operators.cs b/src/SchwabenCode.QuickIO/QuickIOShareInfo.Operators.cs deleted file mode 100644 index d97d895..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOShareInfo.Operators.cs +++ /dev/null @@ -1,25 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIOShareInfo - { - /// - /// Returns a of the current path of this file - /// - /// - public QuickIODirectoryInfo AsDirectoryInfo() - { - Contract.Requires( !String.IsNullOrWhiteSpace( FullName ) ); - Contract.Ensures( Contract.Result() != null ); - - return new QuickIODirectoryInfo( FullName ); - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/QuickIOShareInfo.cs b/src/SchwabenCode.QuickIO/QuickIOShareInfo.cs deleted file mode 100644 index c541bd2..0000000 --- a/src/SchwabenCode.QuickIO/QuickIOShareInfo.cs +++ /dev/null @@ -1,116 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - /// - /// Information about a local share - /// - public partial class QuickIOShareInfo - { - /// - /// Called by enumeration - /// - /// Servername - /// Name of Share - /// Type of share - /// Comment or smth - internal QuickIOShareInfo( String server, String shareName, QuickIOShareType shareType, String remark ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( server ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( shareName ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( remark ) ); - - if( QuickIOShareType.Special == shareType && "IPC$" == shareName ) - { - shareType = QuickIOShareType.IPC; - } - - Server = server; - ShareName = shareName; - ShareType = shareType; - Remark = remark; - } - - /// - /// The name of the computer that this share belongs to - /// - public String Server { get; private set; } - - /// - /// QuickIOShareInfo name - /// - public String ShareName { get; private set; } - - /// - /// QuickIOShareInfo type - /// - public QuickIOShareType ShareType { get; private set; } - - /// - /// Comment - /// - public String Remark { get; private set; } - - /// - /// Returns true if this is a file system share - /// - public bool IsFileSystem - { - get - { - Contract.Requires( !String.IsNullOrWhiteSpace( ShareName ) ); - - return - // DISK - ( ShareType == QuickIOShareType.Disk ) - // OR SHARETYPE and NAME - || QuickIOShareType.Special == ShareType && !String.IsNullOrEmpty( ShareName ); - } - } - - - /// - /// Returns the path to this share - /// - /// - public override string ToString() - { - Contract.Requires( !String.IsNullOrWhiteSpace( FullName ) ); - Contract.Ensures( !String.IsNullOrWhiteSpace( Contract.Result() ) ); - - return FullName; - } - - /// - /// Returns the path in regular format (\\server\share\) - /// - private string _fullName; - /// - /// Returns the Fullname - /// - public string FullName - { - get - { - Contract.Requires( !String.IsNullOrWhiteSpace( ShareName ) ); - Contract.Ensures( !String.IsNullOrWhiteSpace( Contract.Result() ) ); - Contract.Ensures( Contract.Result() != null ); - - if( _fullName == null ) - { - string name = ( String.IsNullOrEmpty( Server ) ? Environment.MachineName : Server ); - - _fullName = $@"\\{name}\{ShareName}"; - } - - return _fullName; - } - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/SchwabenCode.QuickIO.csproj b/src/SchwabenCode.QuickIO/SchwabenCode.QuickIO.csproj deleted file mode 100644 index f4a379d..0000000 --- a/src/SchwabenCode.QuickIO/SchwabenCode.QuickIO.csproj +++ /dev/null @@ -1,291 +0,0 @@ - - - - - Debug - AnyCPU - {B33DBCEE-42F4-4570-B4EF-5412CE4A4BDA} - Library - Properties - SchwabenCode.QuickIO - SchwabenCode.QuickIO - v4.6 - 512 - - - NET46 - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - bin\Debug\SchwabenCode.QuickIO.XML - - - NET46 - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - bin\Release\SchwabenCode.QuickIO.XML - - - - NET40 - pdbonly - v4.0 - true - NET40;NET40_OR_GREATER; - ..\..\_artifacts\SchwabenCode.QuickIO\$(Configuration)\$(Framework)AnyCPU - ..\..\_artifacts\SchwabenCode.QuickIO\$(Configuration)\$(Framework)AnyCPU\SchwabenCode.QuickIO.xml - - - NET45 - pdbonly - v4.5 - true - NET40;NET40_OR_GREATER;NET45;NET45_OR_GREATER; - ..\..\_artifacts\SchwabenCode.QuickIO\$(Configuration)\$(Framework)AnyCPU - ..\..\_artifacts\SchwabenCode.QuickIO\$(Configuration)\$(Framework)AnyCPU\SchwabenCode.QuickIO.xml - - - NET46 - pdbonly - v4.6 - true - NET40;NET40_OR_GREATER;NET45;NET45_OR_GREATER;NET46;NET46_OR_GREATER - ..\..\_artifacts\SchwabenCode.QuickIO\$(Configuration)\$(Framework)AnyCPU - ..\..\_artifacts\SchwabenCode.QuickIO\$(Configuration)\$(Framework)AnyCPU\SchwabenCode.QuickIO.xml - - - - - - - - - - - - - - True - True - QuickIODirectory.Attributes.tt - - - True - True - QuickIODirectory.FileTime.tt - - - True - True - QuickIODirectory.Root.tt - - - True - True - QuickIOFile.Attributes.tt - - - True - True - QuickIOFile.FileTime.tt - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - True - True - QuickIOFile.Root.tt - - - True - True - SaveOutput.tt - - - True - True - StaticAttributeMethods.tt - - - True - True - StaticFileTimeMethods.tt - - - True - True - StaticRootMethods.tt - - - - - - - - - - - - - - - - - - TextTemplatingFileGenerator - QuickIODirectory.Attributes.cs - - - TextTemplatingFileGenerator - QuickIODirectory.FileTime.cs - - - TextTemplatingFileGenerator - QuickIODirectory.Root.cs - - - TextTemplatingFileGenerator - QuickIOFile.Attributes.cs - - - TextTemplatingFileGenerator - QuickIOFile.FileTime.cs - - - TextTemplatingFileGenerator - QuickIOFile.Root.cs - - - TextTemplatingFileGenerator - SaveOutput.cs - - - TextTemplatingFileGenerator - StaticAttributeMethods.cs - - - TextTemplatingFileGenerator - StaticFileTimeMethods.cs - - - TextTemplatingFileGenerator - StaticRootMethods.cs - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Win32/IWin32ApiShareInfo.cs b/src/SchwabenCode.QuickIO/Win32/IWin32ApiShareInfo.cs deleted file mode 100644 index 9378918..0000000 --- a/src/SchwabenCode.QuickIO/Win32/IWin32ApiShareInfo.cs +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; - -namespace SchwabenCode.QuickIO.Win32 -{ - public interface IWin32ApiShareInfo - { - /// - /// Returns the share name - /// - String GetShareName(); - - /// - /// Returns the share name - /// - QuickIOShareType GetShareType(); - - /// - /// Returns the remark - /// - String GetRemark(); - } -} diff --git a/src/SchwabenCode.QuickIO/Win32/Win32ApiShareInfoAdmin.cs b/src/SchwabenCode.QuickIO/Win32/Win32ApiShareInfoAdmin.cs deleted file mode 100644 index 3581bfe..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32ApiShareInfoAdmin.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Runtime.InteropServices; - -namespace SchwabenCode.QuickIO.Win32 -{ - /// - /// Gets the complete share information. Requires admin priviles. - /// - /// See http://msdn.microsoft.com/en-us/library/windows/desktop/bb525408(v=vs.85).aspx - [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Unicode )] - public struct Win32ApiShareInfoAdmin: IWin32ApiShareInfo - { - [MarshalAs( UnmanagedType.LPWStr )] - public String ShareName; - public QuickIOShareType ShareType; - [MarshalAs( UnmanagedType.LPWStr )] - public String Remark; - public Int32 Permissions; - public Int32 MaxUsers; - public Int32 CurrentUsers; - [MarshalAs( UnmanagedType.LPWStr )] - public String Path; - [MarshalAs( UnmanagedType.LPWStr )] - public String Password; - - public string GetShareName() { return ShareName; } - public QuickIOShareType GetShareType() { return ShareType; } - public string GetRemark() { return Remark; } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Win32/Win32ApiShareInfoNormal.cs b/src/SchwabenCode.QuickIO/Win32/Win32ApiShareInfoNormal.cs deleted file mode 100644 index 3e09dbe..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32ApiShareInfoNormal.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Runtime.InteropServices; - -namespace SchwabenCode.QuickIO.Win32 -{ - /// - /// Use this Info bag if call with admin privilegs fails (fallback) - /// - /// See http://msdn.microsoft.com/en-us/library/windows/desktop/bb525407(v=vs.85).aspx - [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Unicode )] - public struct Win32ApiShareInfoNormal: IWin32ApiShareInfo - { - [MarshalAs( UnmanagedType.LPWStr )] - public String ShareName; - public QuickIOShareType ShareType; - [MarshalAs( UnmanagedType.LPWStr )] - public String Remark; - - /// - /// Returns the share name - /// - public string GetShareName() { return ShareName; } - public QuickIOShareType GetShareType() { return ShareType; } - public string GetRemark() { return Remark; } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Win32/Win32ErrorCodes.cs b/src/SchwabenCode.QuickIO/Win32/Win32ErrorCodes.cs deleted file mode 100644 index b1aa8ad..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32ErrorCodes.cs +++ /dev/null @@ -1,522 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.ComponentModel; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO.Win32 -{ - /// - /// Win32 Error Code Collection - /// - public class Win32ErrorCodes - { - public const Int32 ERROR_ACCESS_DENIED = 5; - public const Int32 ERROR_ADAP_HDW_ERR = 57; - public const Int32 ERROR_ALREADY_ASSIGNED = 85; - public const Int32 ERROR_ALREADY_EXISTS = 183; - public const Int32 ERROR_ARENA_TRASHED = 7; - public const Int32 ERROR_ATOMIC_LOCKS_NOT_SUPPORTED = 174; - public const Int32 ERROR_AUTODATASEG_EXCEEDS_64k = 199; - public const Int32 ERROR_BAD_ARGUMENTS = 160; - public const Int32 ERROR_BAD_COMMAND = 22; - public const Int32 ERROR_BAD_DEV_TYPE = 66; - public const Int32 ERROR_BAD_DRIVER_LEVEL = 119; - public const Int32 ERROR_BAD_ENVIRONMENT = 10; - public const Int32 ERROR_BAD_EXE_FORMAT = 193; - public const Int32 ERROR_BAD_FILE_TYPE = 222; - public const Int32 ERROR_BAD_FORMAT = 11; - public const Int32 ERROR_BAD_LENGTH = 24; - public const Int32 ERROR_BAD_NET_NAME = 67; - public const Int32 ERROR_BAD_NET_RESP = 58; - public const Int32 ERROR_BAD_NETPATH = 53; - public const Int32 ERROR_BAD_PATHNAME = 161; - public const Int32 ERROR_BAD_PIPE = 230; - public const Int32 ERROR_BAD_REM_ADAP = 60; - public const Int32 ERROR_BAD_THREADID_ADDR = 159; - public const Int32 ERROR_BAD_UNIT = 20; - public const Int32 ERROR_BROKEN_PIPE = 109; - public const Int32 ERROR_BUFFER_OVERFLOW = 111; - public const Int32 ERROR_BUSY_DRIVE = 142; - public const Int32 ERROR_BUSY = 170; - public const Int32 ERROR_CALL_NOT_IMPLEMENTED = 120; - public const Int32 ERROR_CANCEL_VIOLATION = 173; - public const Int32 ERROR_CANNOT_COPY = 266; - public const Int32 ERROR_CANNOT_MAKE = 82; - public const Int32 ERROR_CHECKOUT_REQUIRED = 221; - public const Int32 ERROR_CHILD_NOT_COMPLETE = 129; - public const Int32 ERROR_CRC = 23; - public const Int32 ERROR_CURRENT_DIRECTORY = 16; - public const Int32 ERROR_DELETE_PENDING = 303; - public const Int32 ERROR_DEV_NOT_EXIST = 55; - public const Int32 ERROR_DIR_NOT_EMPTY = 145; - public const Int32 ERROR_DIR_NOT_ROOT = 144; - public const Int32 ERROR_DIRECT_ACCESS_HANDLE = 130; - public const Int32 ERROR_DIRECTORY = 267; - public const Int32 ERROR_DISCARDED = 157; - public const Int32 ERROR_DISK_CHANGE = 107; - public const Int32 ERROR_DISK_FULL = 112; - public const Int32 ERROR_DISK_TOO_FRAGMENTED = 302; - public const Int32 ERROR_DRIVE_LOCKED = 108; - public const Int32 ERROR_DUP_NAME = 52; - public const Int32 ERROR_DYNLINK_FROM_INVALID_RING = 196; - public const Int32 ERROR_EA_FILE_CORRUPT = 276; - public const Int32 ERROR_EA_LIST_INCONSISTENT = 255; - public const Int32 ERROR_EA_TABLE_FULL = 277; - public const Int32 ERROR_EAS_DIDNT_FIT = 275; - public const Int32 ERROR_EAS_NOT_SUPPORTED = 282; - public const Int32 ERROR_ENVVAR_NOT_FOUND = 203; - public const Int32 ERROR_EXCL_SEM_ALREADY_OWNED = 101; - public const Int32 ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY = 217; - public const Int32 ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY = 218; - public const Int32 ERROR_EXE_MACHINE_TYPE_MISMATCH = 216; - public const Int32 ERROR_EXE_MARKED_INVALID = 192; - public const Int32 ERROR_FAIL_I24 = 83; - public const Int32 ERROR_FAIL_NOACTION_REBOOT = 350; - public const Int32 ERROR_FAIL_RESTART = 352; - public const Int32 ERROR_FAIL_SHUTDOWN = 351; - public const Int32 ERROR_FILE_CHECKED_OUT = 220; - public const Int32 ERROR_FILE_EXISTS = 80; - public const Int32 ERROR_FILE_NOT_FOUND = 2; - public const Int32 ERROR_FILE_TOO_LARGE = 223; - public const Int32 ERROR_FILENAME_EXCED_RANGE = 206; - public const Int32 ERROR_FORMS_AUTH_REQUIRED = 224; - public const Int32 ERROR_GEN_FAILURE = 31; - public const Int32 ERROR_HANDLE_DISK_FULL = 39; - public const Int32 ERROR_HANDLE_EOF = 38; - public const Int32 ERROR_IMAGE_SUBSYSTEM_NOT_PRESENT = 308; - public const Int32 ERROR_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING = 304; - public const Int32 ERROR_INFLOOP_IN_RELOC_CHAIN = 202; - public const Int32 ERROR_INSUFFICIENT_BUFFER = 122; - public const Int32 ERROR_INVALID_ACCESS = 12; - public const Int32 ERROR_INVALID_ADDRESS = 487; - public const Int32 ERROR_INVALID_AT_INTERRUPT_TIME = 104; - public const Int32 ERROR_INVALID_BLOCK = 9; - public const Int32 ERROR_INVALID_CATEGORY = 117; - public const Int32 ERROR_INVALID_DATA = 13; - public const Int32 ERROR_INVALID_DRIVE = 15; - public const Int32 ERROR_INVALID_EA_HANDLE = 278; - public const Int32 ERROR_INVALID_EA_NAME = 254; - public const Int32 ERROR_INVALID_EVENT_COUNT = 151; - public const Int32 ERROR_INVALID_EXE_SIGNATURE = 191; - public const Int32 ERROR_INVALID_FLAG_NUMBER = 186; - public const Int32 ERROR_INVALID_FUNCTION = 1; - public const Int32 ERROR_INVALID_HANDLE = 6; - public const Int32 ERROR_INVALID_LEVEL = 124; - public const Int32 ERROR_INVALID_LIST_FORMAT = 153; - public const Int32 ERROR_INVALID_LOCK_RANGE = 307; - public const Int32 ERROR_INVALID_MINALLOCSIZE = 195; - public const Int32 ERROR_INVALID_MODULETYPE = 190; - public const Int32 ERROR_INVALID_NAME = 123; - public const Int32 ERROR_INVALID_OPLOCK_PROTOCOL = 301; - public const Int32 ERROR_INVALID_ORDINAL = 182; - public const Int32 ERROR_INVALID_PARAMETER = 87; - public const Int32 ERROR_INVALID_PASSWORD = 86; - public const Int32 ERROR_INVALID_SEGDPL = 198; - public const Int32 ERROR_INVALID_SEGMENT_NUMBER = 180; - public const Int32 ERROR_INVALID_SIGNAL_NUMBER = 209; - public const Int32 ERROR_INVALID_STACKSEG = 189; - public const Int32 ERROR_INVALID_STARTING_CODESEG = 188; - public const Int32 ERROR_INVALID_TARGET_HANDLE = 114; - public const Int32 ERROR_INVALID_VERIFY_SWITCH = 118; - public const Int32 ERROR_IOPL_NOT_ENABLED = 197; - public const Int32 ERROR_IS_JOIN_PATH = 147; - public const Int32 ERROR_IS_JOIN_TARGET = 133; - public const Int32 ERROR_IS_JOINED = 134; - public const Int32 ERROR_IS_SUBST_PATH = 146; - public const Int32 ERROR_IS_SUBST_TARGET = 149; - public const Int32 ERROR_IS_SUBSTED = 135; - public const Int32 ERROR_ITERATED_DATA_EXCEEDS_64k = 194; - public const Int32 ERROR_JOIN_TO_JOIN = 138; - public const Int32 ERROR_JOIN_TO_SUBST = 140; - public const Int32 ERROR_LABEL_TOO_LONG = 154; - public const Int32 ERROR_LOCK_FAILED = 167; - public const Int32 ERROR_LOCK_VIOLATION = 33; - public const Int32 ERROR_LOCKED = 212; - public const Int32 ERROR_MAX_SESSIONS_REACHED = 353; - public const Int32 ERROR_MAX_THRDS_REACHED = 164; - public const Int32 ERROR_META_EXPANSION_TOO_LONG = 208; - public const Int32 ERROR_MOD_NOT_FOUND = 126; - public const Int32 ERROR_MORE_DATA = 234; - public const Int32 ERROR_MR_MID_NOT_FOUND = 317; - public const Int32 ERROR_NEGATIVE_SEEK = 131; - public const Int32 ERROR_NESTING_NOT_ALLOWED = 215; - public const Int32 ERROR_NET_WRITE_FAULT = 88; - public const Int32 ERROR_NETNAME_DELETED = 64; - public const Int32 ERROR_NETWORK_ACCESS_DENIED = 65; - public const Int32 ERROR_NETWORK_BUSY = 54; - public const Int32 ERROR_NO_DATA = 232; - public const Int32 ERROR_NO_MORE_FILES = 18; - public const Int32 ERROR_NO_MORE_ITEMS = 259; - public const Int32 ERROR_NO_MORE_SEARCH_HANDLES = 113; - public const Int32 ERROR_NO_PROC_SLOTS = 89; - public const Int32 ERROR_NO_SIGNAL_SENT = 205; - public const Int32 ERROR_NO_SPOOL_SPACE = 62; - public const Int32 ERROR_NO_VOLUME_LABEL = 125; - public const Int32 ERROR_NOT_DOS_DISK = 26; - public const Int32 ERROR_NOT_ENOUGH_MEMORY = 8; - public const Int32 ERROR_NOT_JOINED = 136; - public const Int32 ERROR_NOT_LOCKED = 158; - public const Int32 ERROR_NOT_OWNER = 288; - public const Int32 ERROR_NOT_READY = 21; - public const Int32 ERROR_NOT_SAME_DEVICE = 17; - public const Int32 ERROR_NOT_SUBSTED = 137; - public const Int32 ERROR_NOT_SUPPORTED = 50; - public const Int32 ERROR_NOTIFICATION_GUID_ALREADY_DEFINED = 309; - public const Int32 ERROR_OPEN_FAILED = 110; - public const Int32 ERROR_OPLOCK_NOT_GRANTED = 300; - public const Int32 ERROR_OUT_OF_PAPER = 28; - public const Int32 ERROR_OUT_OF_STRUCTURES = 84; - public const Int32 ERROR_OUTOFMEMORY = 14; - public const Int32 ERROR_PARTIAL_COPY = 299; - public const Int32 ERROR_PATH_BUSY = 148; - public const Int32 ERROR_PATH_NOT_FOUND = 3; - public const Int32 ERROR_PIPE_BUSY = 231; - public const Int32 ERROR_PIPE_LOCAL = 229; - public const Int32 ERROR_PIPE_NOT_CONNECTED = 233; - public const Int32 ERROR_PRINT_CANCELLED = 63; - public const Int32 ERROR_PRINTQ_FULL = 61; - public const Int32 ERROR_PROC_NOT_FOUND = 127; - public const Int32 ERROR_PROCESS_MODE_ALREADY_BACKGROUND = 402; - public const Int32 ERROR_PROCESS_MODE_NOT_BACKGROUND = 403; - public const Int32 ERROR_READ_FAULT = 30; - public const Int32 ERROR_REDIR_PAUSED = 72; - public const Int32 ERROR_RELOC_CHAIN_XEEDS_SEGLIM = 201; - public const Int32 ERROR_REM_NOT_LIST = 51; - public const Int32 ERROR_REQ_NOT_ACCEP = 71; - public const Int32 ERROR_RING2_STACK_IN_USE = 207; - public const Int32 ERROR_RING2SEG_MUST_BE_MOVABLE = 200; - public const Int32 ERROR_SAME_DRIVE = 143; - public const Int32 ERROR_SCOPE_NOT_FOUND = 318; - public const Int32 ERROR_SECTOR_NOT_FOUND = 27; - public const Int32 ERROR_SECURITY_STREAM_IS_INCONSISTENT = 306; - public const Int32 ERROR_SEEK_ON_DEVICE = 132; - public const Int32 ERROR_SEEK = 25; - public const Int32 ERROR_SEM_IS_SET = 102; - public const Int32 ERROR_SEM_NOT_FOUND = 187; - public const Int32 ERROR_SEM_OWNER_DIED = 105; - public const Int32 ERROR_SEM_TIMEOUT = 121; - public const Int32 ERROR_SEM_USER_LIMIT = 106; - public const Int32 ERROR_SHARING_BUFFER_EXCEEDED = 36; - public const Int32 ERROR_SHARING_PAUSED = 70; - public const Int32 ERROR_SHARING_VIOLATION = 32; - public const Int32 ERROR_SHORT_NAMES_NOT_ENABLED_ON_VOLUME = 305; - public const Int32 ERROR_SIGNAL_PENDING = 162; - public const Int32 ERROR_SIGNAL_REFUSED = 156; - public const Int32 ERROR_SUBST_TO_JOIN = 141; - public const Int32 ERROR_SUBST_TO_SUBST = 139; - public const Int32 ERROR_SUCCESS = 0; - public const Int32 ERROR_SYSTEM_TRACE = 150; - public const Int32 ERROR_THREAD_1_INACTIVE = 210; - public const Int32 ERROR_THREAD_MODE_ALREADY_BACKGROUND = 400; - public const Int32 ERROR_THREAD_MODE_NOT_BACKGROUND = 401; - public const Int32 ERROR_TOO_MANY_CMDS = 56; - public const Int32 ERROR_TOO_MANY_MODULES = 214; - public const Int32 ERROR_TOO_MANY_MUXWAITERS = 152; - public const Int32 ERROR_TOO_MANY_NAMES = 68; - public const Int32 ERROR_TOO_MANY_OPEN_FILES = 4; - public const Int32 ERROR_TOO_MANY_POSTS = 298; - public const Int32 ERROR_TOO_MANY_SEM_REQUESTS = 103; - public const Int32 ERROR_TOO_MANY_SEMAPHORES = 100; - public const Int32 ERROR_TOO_MANY_SESS = 69; - public const Int32 ERROR_TOO_MANY_TCBS = 155; - public const Int32 ERROR_UNEXP_NET_ERR = 59; - public const Int32 ERROR_VC_DISCONNECTED = 240; - public const Int32 ERROR_VIRUS_DELETED = 226; - public const Int32 ERROR_VIRUS_INFECTED = 225; - public const Int32 ERROR_WAIT_NO_CHILDREN = 128; - public const Int32 ERROR_WRITE_FAULT = 29; - public const Int32 ERROR_WRITE_PROTECT = 19; - public const Int32 ERROR_WRONG_DISK = 34; - public const Int32 WAIT_TIMEOUT = 258; - - - /// - /// Exception Mapping - /// - /// - /// errorCode - public static void NativeExceptionMapping( String path, Int32 errorCode ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - if( errorCode == Win32ErrorCodes.ERROR_SUCCESS ) - { - return; - } - - string affectedPath = path; - - // http://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx - - switch( errorCode ) - { - case Win32ErrorCodes.ERROR_PATH_NOT_FOUND: - case Win32ErrorCodes.ERROR_FILE_NOT_FOUND: - throw new PathNotFoundException( Win32ErrorCodes.FormatMessage( errorCode ), affectedPath ); - - case Win32ErrorCodes.ERROR_ALREADY_EXISTS: - throw new PathAlreadyExistsException( Win32ErrorCodes.FormatMessage( errorCode ), affectedPath ); - - case Win32ErrorCodes.ERROR_INVALID_NAME: - case Win32ErrorCodes.ERROR_DIRECTORY: - throw new InvalidPathException( Win32ErrorCodes.FormatMessage( errorCode ), affectedPath ); - - case Win32ErrorCodes.ERROR_REM_NOT_LIST: - case Win32ErrorCodes.ERROR_NETWORK_BUSY: - case Win32ErrorCodes.ERROR_BUSY: - case Win32ErrorCodes.ERROR_PATH_BUSY: - throw new FileSystemIsBusyException( Win32ErrorCodes.FormatMessage( errorCode ), affectedPath ); - - case Win32ErrorCodes.ERROR_DIR_NOT_EMPTY: - throw new DirectoryNotEmptyException( Win32ErrorCodes.FormatMessage( errorCode ), affectedPath ); - - case Win32ErrorCodes.ERROR_ACCESS_DENIED: - case Win32ErrorCodes.ERROR_NETWORK_ACCESS_DENIED: - throw new UnauthorizedAccessException( "Access to '" + affectedPath + "' denied.", new Win32Exception( errorCode ) ); - - case Win32ErrorCodes.ERROR_CURRENT_DIRECTORY: - case Win32ErrorCodes.ERROR_CANNOT_MAKE: - throw new Exception( Win32ErrorCodes.FormatMessage( errorCode ) + affectedPath + "'.", new Win32Exception( errorCode ) ); - - default: - throw new Exception( "Error on '" + affectedPath + "': See InnerException for details.", new Win32Exception( errorCode ) ); - } - } - - /// - /// Formats to a message - /// - /// ErrorCode - /// Message or "Unknown" if is not handles - public static string FormatMessage( Int32 errorCode ) - { - switch ( errorCode ) - { - case 0: return "The operation completed successfully."; - case 1: return "Incorrect function."; - case 10: return "The environment is incorrect."; - case 100: return "Cannot create another system semaphore."; - case 101: return "The exclusive semaphore is owned by another process."; - case 102: return "The semaphore is set and cannot be closed."; - case 103: return "The semaphore cannot be set again."; - case 104: return "Cannot request exclusive semaphores at interrupt time."; - case 105: return "The previous ownership of this semaphore has ended."; - case 106: return "Insert the diskette for drive %1."; - case 107: return "The program stopped because an alternate diskette was not inserted."; - case 108: return "The disk is in use or locked by another process."; - case 109: return "The pipe has been ended."; - case 11: return "An attempt was made to load a program with an incorrect format."; - case 110: return "The system cannot open the device or file specified."; - case 111: return "The file name is too long."; - case 112: return "There is not enough space on the disk."; - case 113: return "No more internal file identifiers available."; - case 114: return "The target internal file identifier is incorrect."; - case 117: return "The IOCTL call made by the application program is not correct."; - case 118: return "The verify-on-write switch parameter value is not correct."; - case 119: return "The system does not support the command requested."; - case 12: return "The access code is invalid."; - case 120: return "This function is not supported on this system."; - case 121: return "The semaphore timeout period has expired."; - case 122: return "The data area passed to a system call is too small."; - case 123: return "The filename, directory name, or volume label syntax is incorrect."; - case 124: return "The system call level is not correct."; - case 125: return "The disk has no volume label."; - case 126: return "The specified module could not be found."; - case 127: return "The specified procedure could not be found."; - case 128: return "There are no child processes to wait for."; - case 129: return "The %1 application cannot be run in Win32 mode."; - case 13: return "The data is invalid."; - case 130: return "Attempt to use a file handle to an open disk partition for an operation other than raw disk I/O."; - case 131: return "An attempt was made to move the file pointer before the beginning of the file."; - case 132: return "The file pointer cannot be set on the specified device or file."; - case 133: return "A JOIN or SUBST command cannot be used for a drive that contains previously joined drives."; - case 134: return "An attempt was made to use a JOIN or SUBST command on a drive that has already been joined."; - case 135: return "An attempt was made to use a JOIN or SUBST command on a drive that has already been substituted."; - case 136: return "The system tried to delete the JOIN of a drive that is not joined."; - case 137: return "The system tried to delete the substitution of a drive that is not substituted."; - case 138: return "The system tried to join a drive to a directory on a joined drive."; - case 139: return "The system tried to substitute a drive to a directory on a substituted drive."; - case 14: return "Not enough storage is available to complete this operation."; - case 140: return "The system tried to join a drive to a directory on a substituted drive."; - case 141: return "The system tried to SUBST a drive to a directory on a joined drive."; - case 142: return "The system cannot perform a JOIN or SUBST at this time."; - case 143: return "The system cannot join or substitute a drive to or for a directory on the same drive."; - case 144: return "The directory is not a subdirectory of the root directory."; - case 145: return "The directory is not empty."; - case 146: return "The path specified is being used in a substitute."; - case 147: return "Not enough resources are available to process this command."; - case 148: return "The path specified cannot be used at this time."; - case 149: return "An attempt was made to join or substitute a drive for which a directory on the drive is the target of a previous substitute."; - case 15: return "The system cannot find the drive specified."; - case 150: return "System trace information was not specified in your CONFIG.SYS file, or tracing is disallowed."; - case 151: return "The number of specified semaphore events for DosMuxSemWait is not correct."; - case 152: return "DosMuxSemWait did not execute; too many semaphores are already set."; - case 153: return "The DosMuxSemWait list is not correct."; - case 154: return "The volume label you entered exceeds the label character limit of the target file system."; - case 155: return "Cannot create another thread."; - case 156: return "The recipient process has refused the signal."; - case 157: return "The segment is already discarded and cannot be locked."; - case 158: return "The segment is already unlocked."; - case 159: return "The address for the thread ID is not correct."; - case 16: return "The directory cannot be removed."; - case 160: return "One or more arguments are not correct."; - case 161: return "The specified path is invalid."; - case 162: return "A signal is already pending."; - case 164: return "No more threads can be created in the system."; - case 167: return "Unable to lock a region of a file."; - case 17: return "The system cannot move the file to a different disk drive."; - case 170: return "The requested resource is in use."; - case 173: return "A lock request was not outstanding for the supplied cancel region."; - case 174: return "The file system does not support atomic changes to the lock type."; - case 18: return "There are no more files."; - case 180: return "The system detected a segment number that was not correct."; - case 182: return "The operating system cannot run %1."; - case 183: return "Cannot create a file when that file already exists."; - case 186: return "The flag passed is not correct."; - case 187: return "The specified system semaphore name was not found."; - case 188: return "The operating system cannot run %1."; - case 189: return "The operating system cannot run %1."; - case 19: return "The media is write protected."; - case 190: return "The operating system cannot run %1."; - case 191: return "Cannot run %1 in Win32 mode."; - case 192: return "The operating system cannot run %1."; - case 193: return "is not a valid Win32 application."; - case 194: return "The operating system cannot run %1."; - case 195: return "The operating system cannot run %1."; - case 196: return "The operating system cannot run this application program."; - case 197: return "The operating system is not presently configured to run this application."; - case 198: return "The operating system cannot run %1."; - case 199: return "The operating system cannot run this application program."; - case 2: return "The system cannot find the file specified."; - case 20: return "The system cannot find the device specified."; - case 200: return "The code segment cannot be greater than or equal to 64K."; - case 201: return "The operating system cannot run %1."; - case 202: return "The operating system cannot run %1."; - case 203: return "The system could not find the environment option that was entered."; - case 205: return "No process in the command subtree has a signal handler."; - case 206: return "The filename or extension is too long."; - case 207: return "The ring 2 stack is in use."; - case 208: return "The global filename characters, * or ?, are entered incorrectly or too many global filename characters are specified."; - case 209: return "The signal being posted is not correct."; - case 21: return "The device is not ready."; - case 210: return "The signal handler cannot be set."; - case 212: return "The segment is locked and cannot be reallocated."; - case 214: return "Too many dynamic-link modules are attached to this program or dynamic-link module."; - case 215: return "Cannot nest calls to LoadModule."; - case 216: return "The version of %1 is not compatible with the version you're running. Check your computer's system information to see whether you need a x86 ; or x64 ; version of the program, and then contact the software publisher."; - case 217: return "The image file %1 is signed, unable to modify."; - case 218: return "The image file %1 is strong signed, unable to modify."; - case 22: return "The device does not recognize the command."; - case 220: return "This file is checked out or locked for editing by another user."; - case 221: return "The file must be checked out before saving changes."; - case 222: return "The file type being saved or retrieved has been blocked."; - case 223: return "The file size exceeds the limit allowed and cannot be saved."; - case 224: return "Access Denied. Before opening files in this location, you must first add the web site to your trusted sites list, browse to the web site, and select the option to login automatically."; - case 225: return "Operation did not complete successfully because the file contains a virus."; - case 226: return "This file contains a virus and cannot be opened. Due to the nature of this virus, the file has been removed from this location."; - case 229: return "The pipe is local."; - case 23: return "Data error ;."; - case 230: return "The pipe state is invalid."; - case 231: return "PathMatchAll pipe instances are busy."; - case 232: return "The pipe is being closed."; - case 233: return "No process is on the other end of the pipe."; - case 234: return "More data is available."; - case 24: return "The program issued a command but the command length is incorrect."; - case 240: return "The session was canceled."; - case 25: return "The drive cannot locate a specific area or track on the disk."; - case 254: return "The specified extended attribute name was invalid."; - case 255: return "The extended attributes are inconsistent."; - case 258: return "The wait operation timed out."; - case 259: return "No more data is available."; - case 26: return "The specified disk or diskette cannot be accessed."; - case 266: return "The copy functions cannot be used."; - case 267: return "The directory name is invalid."; - case 27: return "The drive cannot find the sector requested."; - case 275: return "The extended attributes did not fit in the buffer."; - case 276: return "The extended attribute file on the mounted file system is corrupt."; - case 277: return "The extended attribute table file is full."; - case 278: return "The specified extended attribute handle is invalid."; - case 28: return "The printer is out of paper."; - case 282: return "The mounted file system does not support extended attributes."; - case 288: return "Attempt to release mutex not owned by caller."; - case 29: return "The system cannot write to the specified device."; - case 298: return "Too many posts were made to a semaphore."; - case 299: return "Only part of a ReadProcessMemory or WriteProcessMemory request was completed."; - case 3: return "The system cannot find the path specified."; - case 30: return "The system cannot read from the specified device."; - case 300: return "The oplock request is denied."; - case 301: return "An invalid oplock acknowledgment was received by the system."; - case 302: return "The volume is too fragmented to complete this operation."; - case 303: return "The file cannot be opened because it is in the process of being deleted."; - case 304: return "Short name settings may not be changed on this volume due to the global registry setting."; - case 305: return "Short names are not enabled on this volume."; - case 306: return "The security stream for the given volume is in an inconsistent state. Please run CHKDSK on the volume."; - case 307: return "A requested file lock operation cannot be processed due to an invalid byte range."; - case 308: return "The subsystem needed to support the image type is not present."; - case 309: return "The specified file already has a notification GUID associated with it."; - case 31: return "A device attached to the system is not functioning."; - case 317: return "The system cannot find message text for message number 0x%1 in the message file for %2."; - case 318: return "The scope specified was not found."; - case 32: return "The process cannot access the file because it is being used by another process."; - case 33: return "The process cannot access the file because another process has locked a portion of the file."; - case 34: return "The wrong diskette is in the drive. Insert %2 ; into drive %1."; - case 350: return "No action was taken as a system reboot is required."; - case 351: return "The shutdown operation failed."; - case 352: return "The restart operation failed."; - case 353: return "The maximum number of sessions has been reached."; - case 36: return "Too many files opened for sharing."; - case 38: return "Reached the end of the file."; - case 39: return "The disk is full."; - case 4: return "The system cannot open the file."; - case 400: return "The thread is already in background processing mode."; - case 401: return "The thread is not in background processing mode."; - case 402: return "The process is already in background processing mode."; - case 403: return "The process is not in background processing mode."; - case 487: return "Attempt to access invalid address."; - case 5: return "Access is denied."; - case 50: return "The request is not supported."; - case 51: return "Windows cannot find the network path. Verify that the network path is correct and the destination computer is not busy or turned off. If Windows still cannot find the network path, contact your network administrator."; - case 52: return "You were not connected because a duplicate name exists on the network. If joining a domain, go to System in Control Panel to change the computer name and try again. If joining a workgroup, choose another workgroup name."; - case 53: return "The network path was not found."; - case 54: return "The network is busy."; - case 55: return "The specified network resource or device is no longer available."; - case 56: return "The network BIOS command limit has been reached."; - case 57: return "A network adapter hardware error occurred."; - case 58: return "The specified server cannot perform the requested operation."; - case 59: return "An unexpected network error occurred."; - case 6: return "The handle is invalid."; - case 60: return "The remote adapter is not compatible."; - case 61: return "The printer queue is full."; - case 62: return "Space to store the file waiting to be printed is not available on the server."; - case 63: return "Your file waiting to be printed was deleted."; - case 64: return "The specified network name is no longer available."; - case 65: return "Network access is denied."; - case 66: return "The network resource type is not correct."; - case 67: return "The network name cannot be found."; - case 68: return "The name limit for the local computer network adapter card was exceeded."; - case 69: return "The network BIOS session limit was exceeded."; - case 7: return "The storage control blocks were destroyed."; - case 70: return "The remote server has been paused or is in the process of being started."; - case 71: return "No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept."; - case 72: return "The specified printer or disk device has been paused."; - case 8: return "Not enough storage is available to process this command."; - case 80: return "The file exists."; - case 82: return "The directory or file cannot be created."; - case 83: return "Fail on INT 24."; - case 84: return "Storage to process this request is not available."; - case 85: return "The local device name is already in use."; - case 86: return "The specified network password is not correct."; - case 87: return "The parameter is incorrect."; - case 88: return "A write fault occurred on the network."; - case 89: return "The system cannot start another process at this time."; - case 9: return "The storage control block address is invalid."; - - default: return "unknown."; - } - } - } -} diff --git a/src/SchwabenCode.QuickIO/Win32/Win32FileHandle.cs b/src/SchwabenCode.QuickIO/Win32/Win32FileHandle.cs deleted file mode 100644 index f51c37b..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32FileHandle.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Security.Permissions; -using Microsoft.Win32.SafeHandles; - -namespace SchwabenCode.QuickIO.Win32 -{ - /// - /// Provides a class for Win32 safe handle implementations - /// - public sealed class Win32FileHandle : SafeHandleZeroOrMinusOneIsInvalid - { - /// - /// Initializes a new instance of the Win32ApiFileHandle class, specifying whether the handle is to be reliably released. - /// - [SecurityPermission( SecurityAction.LinkDemand, UnmanagedCode = true )] - internal Win32FileHandle() - : base( true ) - { - } - - /// - /// Initializes a new instance of the Win32ApiFileHandle class, specifying whether the handle is to be reliably released. - /// - public Win32FileHandle( IntPtr preExistingHandle, bool ownsHandle ) - : base( ownsHandle ) - { - base.SetHandle( preExistingHandle ); - } - - /// - /// When overridden in a derived class, executes the code required to free the handle. - /// - protected override bool ReleaseHandle() - { - if ( !( IsInvalid || IsClosed ) ) - { - return Win32SafeNativeMethods.FindClose( this ); - } - return ( IsInvalid || IsClosed ); - } - - /// - /// Releases the unmanaged resources used by the Win32ApiFileHandle class specifying whether to perform a normal dispose operation. - /// - protected override void Dispose( bool disposing ) - { - if ( !( IsInvalid || IsClosed ) ) - { - Win32SafeNativeMethods.FindClose( this ); - } - base.Dispose( disposing ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/Win32/Win32FileHandleCollection.cs b/src/SchwabenCode.QuickIO/Win32/Win32FileHandleCollection.cs deleted file mode 100644 index e7e38df..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32FileHandleCollection.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO.Win32 -{ - public class Win32FileHandleCollection : IEnumerable - { - public bool FitlerSystemEntries { get; } - - public string DirectoryPath { get; } - - /// - /// Creates an instance of with given directory path - /// - /// Directory - /// Filters . and .. from system enumeration - public Win32FileHandleCollection( string path, bool filterSystemEntries = true ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - if( String.IsNullOrWhiteSpace( path ) ) - { - throw new ArgumentNullException( nameof( path ) ); - } - - - DirectoryPath = path; - FitlerSystemEntries = filterSystemEntries; - } - - // Implementation for the GetEnumerator method. - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public Win32FileHandleEnumerator GetEnumerator() - { - Contract.Requires( !String.IsNullOrWhiteSpace( DirectoryPath ) ); - Contract.Ensures( Contract.Result() != null ); - - return new Win32FileHandleEnumerator( DirectoryPath, FitlerSystemEntries ); - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Win32/Win32FileHandleEnumerator.cs b/src/SchwabenCode.QuickIO/Win32/Win32FileHandleEnumerator.cs deleted file mode 100644 index ecf10c5..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32FileHandleEnumerator.cs +++ /dev/null @@ -1,171 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Collections.Generic; -using System.Collections; -using System.Runtime.InteropServices; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO.Win32 -{ - /// - /// Provides an file system enumerator for FindFirstFile and FindNextFile - /// - public class Win32FileHandleEnumerator : IEnumerator - { - /// - /// Creates an instance of and sets - /// - public Win32FileHandleEnumerator() - { - _currentFindData = new Win32FindData(); - } - - /// - /// Creates an instance of - /// - /// UNC Path to directory - /// Ignores system entries like . and .. in enumeration and skips them in - internal Win32FileHandleEnumerator( string directoryPath, bool filterSystemEntries = true ) : this() - { - Contract.Requires( !String.IsNullOrWhiteSpace( directoryPath ) ); - if( String.IsNullOrWhiteSpace( directoryPath ) ) - { - throw new ArgumentNullException( nameof( directoryPath ) ); - } - - DirectoryPath = directoryPath; - FilterSystemEntries = filterSystemEntries; - } - - /// - /// The Path to enumerate - /// - public string DirectoryPath { get; } - - /// - /// Indicates the state if system entries like . and .. should be skipped in - /// - public bool FilterSystemEntries { get; } - - /// - /// Current handle found - /// - private Win32FileHandle _currentFileHandle; - - /// - /// Current find data found - /// - private Win32FindData _currentFindData; - - /// - /// Last occured error code - /// - private int _currentErrorCode; - - /// - /// Returns current element - /// - public Win32FileSystemEntry Current - { - get - { - Contract.Ensures( Contract.Result() != null ); - return new Win32FileSystemEntry( _currentFileHandle, _currentFindData ); - } - } - - /// - /// Returns current element - /// - object IEnumerator.Current => this.Current; - - - /// - /// Moves to next element - /// - /// - public bool MoveNext() - { - do - { - // only at start currentFileHandle is null - if( _currentFileHandle == null ) - { - // first call - _currentFileHandle = Win32SafeNativeMethods.FindFirstFile( DirectoryPath, _currentFindData ); - _currentErrorCode = Marshal.GetLastWin32Error(); - } - else - { - // second to n call - _currentFindData = new Win32FindData(); - if( !Win32SafeNativeMethods.FindNextFile( _currentFileHandle, _currentFindData ) ) - { - return false; - } - } - - // Take care of invalid handles - if( _currentFileHandle.IsInvalid ) - { - if( _currentErrorCode != Win32ErrorCodes.ERROR_NO_MORE_FILES ) - { - Win32ErrorCodes.NativeExceptionMapping( DirectoryPath, _currentErrorCode ); - } - - return false; - } - - // skip entries to ignore - } while( FilterSystemEntries && _currentFindData.IsSystemDirectoryEntry() ); - - return true; - } - - /// - /// You cannot reset this enumerator - /// - /// Throws an - /// Method not supported - public void Reset() - { - throw new NotSupportedException(); - } - - #region Dispose - - private bool _disposed; - public void Dispose() - { - Dispose( true ); - GC.SuppressFinalize( this ); - } - - protected virtual void Dispose( bool disposing ) - { - if( _disposed ) - { - return; - } - // dispose all - if( disposing ) - { - _currentFileHandle.Dispose(); - _currentFileHandle = null; - } - - // done - _disposed = true; - } - - ~Win32FileHandleEnumerator() - { - Dispose( false ); - } - } - #endregion Dispise -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Win32/Win32FileSystemEntry.cs b/src/SchwabenCode.QuickIO/Win32/Win32FileSystemEntry.cs deleted file mode 100644 index 283517e..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32FileSystemEntry.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.IO; - -namespace SchwabenCode.QuickIO.Win32 -{ - public class Win32FileSystemEntry - { - public Win32FileSystemEntry( Win32FileHandle fileHandle, Win32FindData findData ) - { - FileHandle = fileHandle; - FindData = findData; - } - - public Win32FileHandle FileHandle { get; } - - public Win32FindData FindData { get; } - - /// - /// Returns name of entry (not fullname!) - /// - public String Name => FindData.cFileName; - - /// - /// Returns all responding to this - /// - public FileAttributes Attributes => FindData.dwFileAttributes; - - /// - /// Returns true if entry is a directory - /// - /// Checks - public Boolean IsDirectory => FindData.IsDirectory(); - - /// - /// Returns true if entry is a file - /// - /// Checks - public Boolean IsFile => FindData.IsFile(); - - /// - /// Returns total size of entry in Bytes - /// - public UInt64 Bytes => FindData.GetBytes(); - - /// - /// Returns type of entry - /// - public QuickIOFileSystemEntryType FileSystemEntryType => FindData.GetFileSystemEntryType(); - - public Boolean IsValidEntry => !FindData.IsSystemDirectoryEntry(); - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Win32/Win32FileSystemEntrySecurityInformation.cs b/src/SchwabenCode.QuickIO/Win32/Win32FileSystemEntrySecurityInformation.cs deleted file mode 100644 index 900785a..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32FileSystemEntrySecurityInformation.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - - -using System; - -namespace SchwabenCode.QuickIO.Win32 -{ - /// - /// Win32 Security Information - /// - [Flags] - public enum Win32FileSystemEntrySecurityInformation : uint - { - OwnerSecurityInformation = 1, - GroupSecurityInformation = 2, - - DaclSecurityInformation = 4, - SaclSecurityInformation = 8, - - UnprotectedSaclSecurityInformation = 0x10000000, - UnprotectedDaclSecurityInformation = 0x20000000, - - ProtectedSaclSecurityInformation = 0x40000000, - ProtectedDaclSecurityInformation = 0x80000000 - } -} diff --git a/src/SchwabenCode.QuickIO/Win32/Win32FileTime.cs b/src/SchwabenCode.QuickIO/Win32/Win32FileTime.cs deleted file mode 100644 index 3e07cb4..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32FileTime.cs +++ /dev/null @@ -1,20 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System.Runtime.InteropServices; - -namespace SchwabenCode.QuickIO.Win32 -{ - /// - /// See http://www.pinvoke.net/default.aspx/Structures/FILETIME.html?diff=y - /// Represents Win32 LongFileTime - /// - [StructLayout( LayoutKind.Sequential )] - public struct Win32FileTime - { - public uint DateTimeLow; - public uint DateTimeHigh; - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/Win32/Win32FindData.cs b/src/SchwabenCode.QuickIO/Win32/Win32FindData.cs deleted file mode 100644 index 8e3ef60..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32FindData.cs +++ /dev/null @@ -1,86 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Runtime.InteropServices; -using System.IO; - -namespace SchwabenCode.QuickIO.Win32 -{ - /// - /// Structure of File Data given by Win32 API - /// - [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Auto )] - [BestFitMapping( false )] - public class Win32FindData - { - /// - /// File Attributes - /// - public FileAttributes dwFileAttributes; - - /// - /// Last Creation Time (Low DateTime) - /// - public uint ftCreationTime_dwLowDateTime; - - /// - /// Last Creation Time (High DateTime) - /// - public uint ftCreationTime_dwHighDateTime; - - /// - /// Last Access Time (Low DateTime) - /// - public uint ftLastAccessTime_dwLowDateTime; - - /// - /// Last Access Time (High DateTime) - /// - public uint ftLastAccessTime_dwHighDateTime; - - /// - /// Last Write Time (Low DateTime) - /// - public uint ftLastWriteTime_dwLowDateTime; - - /// - /// Last Write Time (High DateTime) - /// - public uint ftLastWriteTime_dwHighDateTime; - - /// - /// File Size High - /// - public uint nFileSizeHigh; - - /// - /// File Size Low - /// - public uint nFileSizeLow; - - /// - /// Reserved - /// - public uint dwReserved0; - - /// - /// Reserved - /// - public uint dwReserved1; - - /// - /// File name - /// - [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 260 )] - public string cFileName; - - /// - /// Alternate File Name - /// - [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 14 )] - public string cAlternateFileName; - } -} diff --git a/src/SchwabenCode.QuickIO/Win32/Win32FindDataExtensions.cs b/src/SchwabenCode.QuickIO/Win32/Win32FindDataExtensions.cs deleted file mode 100644 index ff4fb50..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32FindDataExtensions.cs +++ /dev/null @@ -1,121 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; -using System.IO; - -namespace SchwabenCode.QuickIO.Win32 -{ - public static class Win32FindDataExtensions - { - /// - /// Returns true if entry is a directory - /// - /// Checks - public static Boolean IsDirectory( this Win32FindData source ) - { - return ( source.dwFileAttributes & FileAttributes.Directory ) != 0; - } - - /// - /// Returns true if entry is a file - /// - /// Checks - public static Boolean IsFile( this Win32FindData source ) - { - return !IsDirectory( source ); - } - /// - /// Returns total size of entry in Bytes - /// - public static ulong GetBytes( this Win32FindData source ) - { - return ( ( ulong )source.nFileSizeHigh << 32 | source.nFileSizeLow ); - } - - /// - /// Returns type of entry - /// - public static QuickIOFileSystemEntryType GetFileSystemEntryType( this Win32FindData source ) - { - return ( IsDirectory( source ) ? QuickIOFileSystemEntryType.Directory : QuickIOFileSystemEntryType.File ); - } - - /// - /// Gets last write time based on UTC - /// - /// - public static DateTime GetLastWriteTimeUtc( this Win32FindData source ) - { - return ConvertDateTime( source.ftLastWriteTime_dwHighDateTime, source.ftLastWriteTime_dwLowDateTime ); - } - - /// - /// Gets last access time based on UTC - /// - /// - public static DateTime GetLastAccessTimeUtc( this Win32FindData source ) - { - return ConvertDateTime( source.ftLastAccessTime_dwHighDateTime, source.ftLastAccessTime_dwLowDateTime ); - } - - /// - /// Gets the creation time based on UTC - /// - /// - public static DateTime GetCreationTimeUtc( this Win32FindData source ) - { - return ConvertDateTime( source.ftCreationTime_dwHighDateTime, source.ftCreationTime_dwLowDateTime ); - } - - /// - /// Converts the PInvoke information into - /// - /// of - /// of - /// - internal static DateTime ConvertDateTime( UInt32 high, UInt32 low ) - { - return DateTime.FromFileTimeUtc( CombineHighLowInts( high, low ) ); - } - - /// - /// Merges the PInvoke information - /// - /// of - /// of - internal static Int64 CombineHighLowInts( UInt32 high, UInt32 low ) - { - return ( ( ( Int64 )high ) << 0x20 ) | low; - } - - - - /// - /// Converts DateTime to Win32 FileTime format - /// - public static Win32FileTime DateTimeToFiletime( DateTime time ) - { - Win32FileTime ft; - var fileTime = time.ToFileTimeUtc(); - ft.DateTimeLow = ( uint )( fileTime & 0xFFFFFFFF ); - ft.DateTimeHigh = ( uint )( fileTime >> 32 ); - return ft; - } - - /// - /// Checks whether a directory supplied by PINvoke is relevant - /// - /// - /// true if is relevant; otherwise false - public static Boolean IsSystemDirectoryEntry( this Win32FindData win32FindData ) - { - Contract.Requires( win32FindData != null ); - - return ( win32FindData.cFileName == "." || win32FindData.cFileName == ".." ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/Win32/Win32SafeNativeMethods.cs b/src/SchwabenCode.QuickIO/Win32/Win32SafeNativeMethods.cs deleted file mode 100644 index 53d6337..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32SafeNativeMethods.cs +++ /dev/null @@ -1,227 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; -using Microsoft.Win32.SafeHandles; - -namespace SchwabenCode.QuickIO.Win32 -{ - /// - /// Native Methods - take a look on www.pinvoke.net - /// - public static class Win32SafeNativeMethods - { - #region advapi32.dll - [DllImport( "advapi32.dll", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true )] - public static extern uint GetSecurityDescriptorLength( IntPtr byteArray ); - - - [DllImport( "advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode )] - public static extern uint SetNamedSecurityInfo( - string unicodePath, - Win32SecurityObjectType objectType, - Win32FileSystemEntrySecurityInformation securityInfo, - IntPtr sidOwner, - IntPtr sidGroup, - IntPtr dacl, - IntPtr sacl ); - - [DllImport( "advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode )] - public static extern uint GetNamedSecurityInfo( - string unicodePath, - Win32SecurityObjectType securityObjectType, - Win32FileSystemEntrySecurityInformation securityInfo, - out IntPtr sidOwner, - out IntPtr sidGroup, - out IntPtr dacl, - out IntPtr sacl, - out IntPtr securityDescriptor ); - - [DllImport( "advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode )] - public static extern bool ConvertStringSidToSid( String sidString, ref IntPtr sidHandle ); - - [DllImport( "advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode )] - public static extern uint LookupAccountSid( String systemName, IntPtr sidHandle, StringBuilder name, ref int cchName, StringBuilder domainName, ref int cchDomainName, out int peUse ); - - #endregion - - #region kernel32.dll - - /// - /// Sets the last all times for files or directories - /// - [DllImport( "kernel32.dll", SetLastError = true, EntryPoint = "SetFileTime", ExactSpelling = true )] - public static extern Int32 SetAllFileTimes( SafeFileHandle fileHandle, ref long lpCreationTime, ref long lpLastAccessTime, ref long lpLastWriteTime ); - - /// - /// Sets the last creation time for files or directories - /// - [DllImport( "kernel32.dll", SetLastError = true, EntryPoint = "SetFileTime", ExactSpelling = true )] - [return: MarshalAs( UnmanagedType.Bool )] - public static extern bool SetCreationFileTime( SafeFileHandle hFile, ref long lpCreationTime, IntPtr lpLastAccessTime, IntPtr lpLastWriteTime ); - - /// - /// Sets the last acess time for files or directories - /// - [DllImport( "kernel32.dll", SetLastError = true, EntryPoint = "SetFileTime", ExactSpelling = true )] - [return: MarshalAs( UnmanagedType.Bool )] - public static extern bool SetLastAccessFileTime( SafeFileHandle hFile, IntPtr lpCreationTime, ref long lpLastAccessTime, IntPtr lpLastWriteTime ); - - /// - /// Sets the last write time for files or directories - /// - [DllImport( "kernel32.dll", SetLastError = true, EntryPoint = "SetFileTime", ExactSpelling = true )] - [return: MarshalAs( UnmanagedType.Bool )] - public static extern bool SetLastWriteFileTime( SafeFileHandle hFile, IntPtr lpCreationTime, IntPtr lpLastAccessTime, ref long lpLastWriteTime ); - - /// - /// Create directory - /// - [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] - [return: MarshalAs( UnmanagedType.Bool )] - public static extern bool CreateDirectory( string fullName, IntPtr securityAttributes ); - - /// - /// Creates a file / directory or opens an handle for an existing file. - /// If you want to get an handle for an existing folder use with ( 0x02000000 ) as attribute and FileMode ( 0x40000000 | 0x80000000 ) - /// Otherwise it you'll get an invalid handle - /// - [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] - public static extern SafeFileHandle CreateFile( - string fullName, - [MarshalAs( UnmanagedType.U4 )] FileAccess dwDesiredAccess, - [MarshalAs( UnmanagedType.U4 )] FileShare dwShareMode, - IntPtr lpSecurityAttributes, - [MarshalAs( UnmanagedType.U4 )] FileMode dwCreationDisposition, - [MarshalAs( UnmanagedType.U4 )] FileAttributes dwFlagsAndAttributes, - IntPtr hTemplateFile ); - - /// - /// Use this to open an handle for an existing file or directory to change for example the timestamps - /// - [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateFile" )] - public static extern SafeFileHandle OpenReadWriteFileSystemEntryHandle( - string fullName, - uint dwAccess, - [MarshalAs( UnmanagedType.U4 )] FileShare dwShareMode, - IntPtr lpSecurityAttributes, - [MarshalAs( UnmanagedType.U4 )]FileMode dwMode, - uint dwAttribute, - IntPtr hTemplateFile ); - - /// - /// Open handle for appending - ///
- /// FileMode has to be 0x0004 for internal appending mode - ///
- [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateFile" )] - public static extern SafeFileHandle CreateFileForAppend( - string fullName, - [MarshalAs( UnmanagedType.U4 )] uint dwDesiredAccess, - [MarshalAs( UnmanagedType.U4 )] FileShare dwShareMode, - IntPtr lpSecurityAttributes, - [MarshalAs( UnmanagedType.U4 )] FileMode dwCreationDisposition, - [MarshalAs( UnmanagedType.U4 )] FileAttributes dwFlagsAndAttributes, - IntPtr hTemplateFile ); - - /// - /// Finds first file of given path - /// - [DllImport( "kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true )] - public static extern Win32FileHandle FindFirstFile( string fullName, [In, Out] Win32FindData win32FindData ); - - /// - /// Finds next file of current handle - /// - [DllImport( "kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true )] - public static extern bool FindNextFile( Win32FileHandle findFileHandle, [In, Out, MarshalAs( UnmanagedType.LPStruct )] Win32FindData win32FindData ); - - /// - /// Moves a directory - /// - [DllImport( "kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true )] - [return: MarshalAs( UnmanagedType.Bool )] - public static extern bool MoveFile( string fullNameSource, string fullNameTarget ); - - /// - /// Copy file - /// - [DllImport( "kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true )] - [return: MarshalAs( UnmanagedType.Bool )] - public static extern bool CopyFile( string fullNameSource, string fullNameTarget, bool failOnExists ); - - /// - /// Removes a file. - /// - [DllImport( "kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true )] - [return: MarshalAs( UnmanagedType.Bool )] - public static extern bool DeleteFile( string fullName ); - - /// - /// Removes a file. - /// - [DllImport( "kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true )] - [return: MarshalAs( UnmanagedType.Bool )] - public static extern bool RemoveDirectory( string fullName ); - - /// - /// Set File Attributes - /// - [DllImport( "kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true )] - public static extern bool SetFileAttributes( string fullName, uint fileAttributes ); - - /// - /// Gets Attributes of given path - /// - [DllImport( "kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true )] - public static extern uint GetFileAttributes( string fullName ); - - /// - /// Close Hnalde - /// - [DllImport( "kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode )] - public static extern bool FindClose( SafeHandle fileHandle ); - - /// - /// Free unmanaged memory - /// - [DllImport( "kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode )] - public static extern IntPtr LocalFree( IntPtr handle ); - - /// - /// QuickIOShareInfo information - /// - /// - [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] - [return: MarshalAs( UnmanagedType.Bool )] - public static extern bool GetDiskFreeSpaceEx( string uncPath, - out UInt64 freeBytes, - out UInt64 totalBytes, - out UInt64 totalFreeBytes ); - #endregion - - #region netapi32.dll - /// - /// Enumerate shares (NT) - /// - /// http://msdn.microsoft.com/en-us/library/windows/desktop/bb525387(v=vs.85).aspx - [DllImport( "netapi32", CharSet = CharSet.Unicode, SetLastError = true )] - public static extern int NetShareEnum( - string lpServerName, - int dwLevel, - out IntPtr lpBuffer, - int dwPrefMaxLen, - out int entriesRead, - out int totalEntries, - ref int hResume ); - - [DllImport( "netapi32", CharSet = CharSet.Unicode, SetLastError = true )] - public static extern int NetApiBufferFree( IntPtr lpBuffer ); - #endregion - } -} diff --git a/src/SchwabenCode.QuickIO/Win32/Win32SecurityObjectType.cs b/src/SchwabenCode.QuickIO/Win32/Win32SecurityObjectType.cs deleted file mode 100644 index baf4466..0000000 --- a/src/SchwabenCode.QuickIO/Win32/Win32SecurityObjectType.cs +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -namespace SchwabenCode.QuickIO.Win32 -{ - /// - /// Win32 Security Object Type - /// - public enum Win32SecurityObjectType - { - SeUnknownObjectType = 0x0, - SeFileObject = 0x1, - SeService = 0x2, - SePrinter = 0x3, - SeRegistryKey = 0x4, - SeLmshare = 0x5, - SeKernelObject = 0x6, - SeWindowObject = 0x7, - SeDsObject = 0x8, - SeDsObjectAll = 0x9, - SeProviderDefinedObject = 0xa, - SeWmiguidObject = 0xb, - SeRegistryWow6432Key = 0xc - } -} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.Attributes.cs b/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.Attributes.cs deleted file mode 100644 index 051dd17..0000000 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.Attributes.cs +++ /dev/null @@ -1,176 +0,0 @@ - -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - - -using System; -using System.IO; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIODirectory - { - /// - /// Gets the of the directory or file. - /// - /// The path to the directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes( string path , FileAttributes attributes ) - { - QuickIOEngine.SetAttributes( QuickIOPath.ToPathUnc( path ), attributes ); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes( QuickIOPathInfo info, FileAttributes attributes ) - { - QuickIOEngine.SetAttributes( info.FullNameUnc, attributes); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes( QuickIODirectoryInfo info, FileAttributes attributes ) - { - QuickIOEngine.SetAttributes( info.FullNameUnc, attributes); - } - - #region Attributes - /// - /// Gets the of the directory or file. - /// - /// The path to the directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes( string path ) - { - return QuickIOEngine.GetAttributes( QuickIOPath.ToPathUnc (path) ); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes( QuickIOPathInfo info ) - { - return QuickIOEngine.GetAttributes( info.FullNameUnc ); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes( QuickIODirectoryInfo info ) - { - return QuickIOEngine.GetAttributes(info.FullNameUnc); - } - - #endregion - - #region Remove Attribute - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute( string path, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(QuickIOPath.ToPathUnc(path), attribute, out updatedAttributes); - - return result; - } - - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute( QuickIOPathInfo info, FileAttributes attribute) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute( QuickIODirectoryInfo info, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - #endregion - - #region Add Attribute - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute( string path, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(QuickIOPath.ToPathUnc(path), attribute, out updatedAttributes); - - return result; - } - - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute( QuickIOPathInfo info, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute( QuickIODirectoryInfo info, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - #endregion - } -} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.FileTime.cs b/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.FileTime.cs deleted file mode 100644 index 31d96b7..0000000 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.FileTime.cs +++ /dev/null @@ -1,484 +0,0 @@ - -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - - -using System; -using SchwabenCode.QuickIO.Engine; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIODirectory - { - #region Get Creation Time - /// - /// Returns the creation time of the file or directory - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTime( String path ) - { - return GetCreationTimeUtc( path ).ToLocalTime( ); - } - /// - /// Returns the creation time of the file or directory - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTime( QuickIOPathInfo info ) - { - return GetCreationTimeUtc( info ).ToLocalTime( ); - } - /// - /// Returns the creation time of the file or directory - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTime( QuickIODirectoryInfo info ) - { - return GetCreationTimeUtc( info.PathInfo ).ToLocalTime( ); - } - - /// - /// Returns the creation time of the file or directory (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTimeUtc( String path ) - { - return GetCreationTimeUtc( new QuickIOPathInfo( path ) ); - } - /// - /// Returns the creation time of the file or directory (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTimeUtc( QuickIOPathInfo info ) - { - return info.FindData.GetCreationTimeUtc( ); - } - /// - /// Returns the creation time of the file or directory (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTimeUtc( QuickIODirectoryInfo info ) - { - return info.FindData.GetCreationTimeUtc( ); - } - #endregion - - #region Get Last Access Time - /// - /// Returns the time of last access of the file or directory - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTime( String path ) - { - return GetLastAccessTimeUtc( path ).ToLocalTime( ); - } - /// - /// Returns the time of last access of the file or directory - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTime( QuickIOPathInfo info ) - { - return GetLastAccessTimeUtc( info ).ToLocalTime( ); - } - /// - /// Returns the time of last access of the file or directory - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTime( QuickIODirectoryInfo info ) - { - return GetLastAccessTimeUtc( info.PathInfo ).ToLocalTime( ); - } - - /// - /// Returns the time of last access of the file or directory (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTimeUtc( String path ) - { - return GetLastAccessTimeUtc( new QuickIOPathInfo( path ) ); - } - /// - /// Returns the time of last access of the file or directory (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTimeUtc( QuickIOPathInfo info ) - { - return info.FindData.GetLastAccessTimeUtc( ); - } - /// - /// Returns the time of last access of the file or directory (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTimeUtc( QuickIODirectoryInfo info ) - { - return info.FindData.GetLastAccessTimeUtc( ); - } - #endregion - - #region Get Last Write Time - /// - /// Returns the time of the file or directory was last written - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTime( String path ) - { - return GetLastWriteTimeUtc( path ).ToLocalTime( ); - } - /// - /// Returns the time of the file or directory was last written - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTime( QuickIOPathInfo info ) - { - return GetLastWriteTimeUtc( info ).ToLocalTime( ); - } - /// - /// Returns the time of the file or directory was last written - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTime( QuickIODirectoryInfo info ) - { - return GetLastWriteTimeUtc( info.PathInfo ).ToLocalTime( ); - } - - /// - /// Returns the time of the file or directory was last written (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTimeUtc( String path ) - { - return GetLastWriteTimeUtc( new QuickIOPathInfo( path ) ); - } - /// - /// Returns the time of the file or directory was last written (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTimeUtc( QuickIOPathInfo info ) - { - return info.FindData.GetLastWriteTimeUtc( ); - } - /// - /// Returns the time of the file or directory was last written (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTimeUtc( QuickIODirectoryInfo info ) - { - return info.FindData.GetLastWriteTimeUtc( ); - } - #endregion - - #region Set All Times - /// - /// Sets the time the file was created. - /// - /// Affected file or directory - /// The time that is to be used - /// The time that is to be used - /// The time that is to be used - public static void SetAllFileTimes( String path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) - { - QuickIOEngine.SetAllFileTimes( QuickIOPath.ToPathUnc(path), creationTime.ToUniversalTime( ), lastAccessTime.ToUniversalTime( ), lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Sets the time the file was created. - /// - /// Affected file or directory - /// The time that is to be used - /// The time that is to be used - /// The time that is to be used - public static void SetAllFileTimes( QuickIOPathInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) - { - QuickIOEngine.SetAllFileTimes( info.FullNameUnc, creationTime.ToUniversalTime( ), lastAccessTime.ToUniversalTime( ), lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Sets the time the file was created. - /// - /// Affected file or directory - /// The time that is to be used - /// The time that is to be used - /// The time that is to be used - public static void SetAllFileTimes( QuickIODirectoryInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) - { - QuickIOEngine.SetAllFileTimes( info.FullNameUnc, creationTime.ToUniversalTime( ), lastAccessTime.ToUniversalTime( ), lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Sets the dates and times of given directory or file. - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - public static void SetAllFileTimesUtc( String path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetAllFileTimes( QuickIOPath.ToPathUnc( path ), creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ); - } - /// - /// Sets the dates and times of given directory or file. - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - public static void SetAllFileTimesUtc( QuickIOPathInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetAllFileTimes( info.FullNameUnc, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ); - } - /// - /// Sets the dates and times of given directory or file. - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - public static void SetAllFileTimesUtc( QuickIODirectoryInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetAllFileTimes( info.FullNameUnc, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ); - } - #endregion - - #region Set Creation Time - /// - /// Defines the time at which the file or directory was created - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetCreationTime( String path, DateTime creationTime ) - { - QuickIOEngine.SetCreationTimeUtc( QuickIOPath.ToPathUnc(path), creationTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was created - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetCreationTime( QuickIOPathInfo info, DateTime creationTime ) - { - QuickIOEngine.SetCreationTimeUtc( info.FullNameUnc, creationTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was created - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetCreationTime( QuickIODirectoryInfo info, DateTime creationTime ) - { - QuickIOEngine.SetCreationTimeUtc( info.FullNameUnc, creationTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was created (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx - public static void SetCreationTimeUtc( String path, DateTime creationTimeUtc ) - { - QuickIOEngine.SetCreationTimeUtc( QuickIOPath.ToPathUnc(path), creationTimeUtc ); - } - /// - /// Defines the time at which the file or directory was created (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx - public static void SetCreationTimeUtc( QuickIOPathInfo info, DateTime creationTimeUtc ) - { - QuickIOEngine.SetCreationTimeUtc( info.FullNameUnc, creationTimeUtc ); - } - /// - /// Defines the time at which the file or directory was created (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx - public static void SetCreationTimeUtc( QuickIODirectoryInfo info, DateTime creationTimeUtc ) - { - QuickIOEngine.SetCreationTimeUtc( info.FullNameUnc, creationTimeUtc ); - } - #endregion - - #region Set Last Access Time - /// - /// Defines the time at which the file or directory was last accessed - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetLastAccessTime( String path, DateTime lastAccessTime ) - { - QuickIOEngine.SetLastAccessTimeUtc( QuickIOPath.ToPathUnc(path), lastAccessTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last accessed - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx - public static void SetLastAccessTime( QuickIOPathInfo info, DateTime lastAccessTime ) - { - QuickIOEngine.SetLastAccessTimeUtc( info.FullNameUnc, lastAccessTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last accessed - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx - public static void SetLastAccessTime( QuickIODirectoryInfo info, DateTime lastAccessTime ) - { - QuickIOEngine.SetLastAccessTimeUtc( info.FullNameUnc, lastAccessTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last accessed (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx - public static void SetLastAccessTimeUtc( String path, DateTime lastAccessTimeUtc ) - { - QuickIOEngine.SetLastAccessTimeUtc( QuickIOPath.ToPathUnc(path), lastAccessTimeUtc ); - } - /// - /// Defines the time at which the file or directory was last accessed (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx - public static void SetLastAccessTimeUtc( QuickIOPathInfo info, DateTime lastAccessTimeUtc ) - { - QuickIOEngine.SetLastAccessTimeUtc( info.FullNameUnc, lastAccessTimeUtc ); - } - /// - /// Defines the time at which the file or directory was last accessed (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx - public static void SetLastAccessTimeUtc( QuickIODirectoryInfo info, DateTime lastAccessTimeUtc ) - { - QuickIOEngine.SetLastAccessTimeUtc( info.FullNameUnc, lastAccessTimeUtc ); - } - #endregion - - #region Set Last Write Time - /// - /// Defines the time at which the file or directory was last written - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetLastWriteTime( String path, DateTime lastWriteTime ) - { - SetLastWriteTimeUtc( path, lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last written - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx - public static void SetLastWriteTime( QuickIOPathInfo info, DateTime lastWriteTime ) - { - SetLastWriteTimeUtc( info, lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last written - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx - public static void SetLastWriteTime( QuickIODirectoryInfo info, DateTime lastWriteTime ) - { - QuickIOEngine.SetLastWriteTimeUtc( info.FullNameUnc, lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last written (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx - public static void SetLastWriteTimeUtc( String path, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetLastWriteTimeUtc( QuickIOPath.ToPathUnc(path), lastWriteTimeUtc ); - } - /// - /// Defines the time at which the file or directory was last written (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx - public static void SetLastWriteTimeUtc( QuickIOPathInfo info, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetLastWriteTimeUtc( info.FullNameUnc, lastWriteTimeUtc ); - } - /// - /// Defines the time at which the file or directory was last written (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx - public static void SetLastWriteTimeUtc( QuickIODirectoryInfo info, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetLastWriteTimeUtc( info.FullNameUnc, lastWriteTimeUtc ); - } - #endregion - } -} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.Root.cs b/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.Root.cs deleted file mode 100644 index 74944e2..0000000 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIODirectory/QuickIODirectory.Root.cs +++ /dev/null @@ -1,50 +0,0 @@ - -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIODirectory - { - - #region Root - - /// - /// Returns the root information - /// - /// The path of a file or directory. - /// A QuickIOPathInfo that represents the root or null if is root. - /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx - public static QuickIOPathInfo GetDirectoryRoot( string path ) - { - return GetDirectoryRoot( new QuickIOPathInfo ( path ) ); - } - - /// - /// Returns the root information - /// - /// A file or directory. - /// A QuickIOPathInfo that represents the root or null if is root. - /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx - public static QuickIOPathInfo GetDirectoryRoot( QuickIOPathInfo info ) - { - return new QuickIOPathInfo(info.Root); - } - - /// - /// Returns the root information - /// - /// A file or directory. - /// A QuickIOPathInfo that represents the root or null if is root. - /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx - public static QuickIOPathInfo GetDirectoryRoot( QuickIODirectoryInfo info ) - { - return new QuickIOPathInfo(info.Root); - } - - #endregion - } -} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.Attributes.cs b/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.Attributes.cs deleted file mode 100644 index fc8c481..0000000 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.Attributes.cs +++ /dev/null @@ -1,176 +0,0 @@ - -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - - -using System; -using System.IO; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIOFile - { - /// - /// Gets the of the directory or file. - /// - /// The path to the directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes( string path , FileAttributes attributes ) - { - QuickIOEngine.SetAttributes( QuickIOPath.ToPathUnc( path ), attributes ); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes( QuickIOPathInfo info, FileAttributes attributes ) - { - QuickIOEngine.SetAttributes( info.FullNameUnc, attributes); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes( QuickIOFileInfo info, FileAttributes attributes ) - { - QuickIOEngine.SetAttributes( info.FullNameUnc, attributes); - } - - #region Attributes - /// - /// Gets the of the directory or file. - /// - /// The path to the directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes( string path ) - { - return QuickIOEngine.GetAttributes( QuickIOPath.ToPathUnc (path) ); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes( QuickIOPathInfo info ) - { - return QuickIOEngine.GetAttributes( info.FullNameUnc ); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes( QuickIOFileInfo info ) - { - return QuickIOEngine.GetAttributes(info.FullNameUnc); - } - - #endregion - - #region Remove Attribute - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute( string path, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(QuickIOPath.ToPathUnc(path), attribute, out updatedAttributes); - - return result; - } - - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute( QuickIOPathInfo info, FileAttributes attribute) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute( QuickIOFileInfo info, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - #endregion - - #region Add Attribute - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute( string path, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(QuickIOPath.ToPathUnc(path), attribute, out updatedAttributes); - - return result; - } - - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute( QuickIOPathInfo info, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute( QuickIOFileInfo info, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - #endregion - } -} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.FileTime.cs b/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.FileTime.cs deleted file mode 100644 index 2433691..0000000 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.FileTime.cs +++ /dev/null @@ -1,484 +0,0 @@ - -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - - -using System; -using SchwabenCode.QuickIO.Engine; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIOFile - { - #region Get Creation Time - /// - /// Returns the creation time of the file or directory - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTime( String path ) - { - return GetCreationTimeUtc( path ).ToLocalTime( ); - } - /// - /// Returns the creation time of the file or directory - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTime( QuickIOPathInfo info ) - { - return GetCreationTimeUtc( info ).ToLocalTime( ); - } - /// - /// Returns the creation time of the file or directory - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTime( QuickIOFileInfo info ) - { - return GetCreationTimeUtc( info.PathInfo ).ToLocalTime( ); - } - - /// - /// Returns the creation time of the file or directory (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTimeUtc( String path ) - { - return GetCreationTimeUtc( new QuickIOPathInfo( path ) ); - } - /// - /// Returns the creation time of the file or directory (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTimeUtc( QuickIOPathInfo info ) - { - return info.FindData.GetCreationTimeUtc( ); - } - /// - /// Returns the creation time of the file or directory (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTimeUtc( QuickIOFileInfo info ) - { - return info.FindData.GetCreationTimeUtc( ); - } - #endregion - - #region Get Last Access Time - /// - /// Returns the time of last access of the file or directory - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTime( String path ) - { - return GetLastAccessTimeUtc( path ).ToLocalTime( ); - } - /// - /// Returns the time of last access of the file or directory - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTime( QuickIOPathInfo info ) - { - return GetLastAccessTimeUtc( info ).ToLocalTime( ); - } - /// - /// Returns the time of last access of the file or directory - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTime( QuickIOFileInfo info ) - { - return GetLastAccessTimeUtc( info.PathInfo ).ToLocalTime( ); - } - - /// - /// Returns the time of last access of the file or directory (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTimeUtc( String path ) - { - return GetLastAccessTimeUtc( new QuickIOPathInfo( path ) ); - } - /// - /// Returns the time of last access of the file or directory (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTimeUtc( QuickIOPathInfo info ) - { - return info.FindData.GetLastAccessTimeUtc( ); - } - /// - /// Returns the time of last access of the file or directory (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTimeUtc( QuickIOFileInfo info ) - { - return info.FindData.GetLastAccessTimeUtc( ); - } - #endregion - - #region Get Last Write Time - /// - /// Returns the time of the file or directory was last written - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTime( String path ) - { - return GetLastWriteTimeUtc( path ).ToLocalTime( ); - } - /// - /// Returns the time of the file or directory was last written - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTime( QuickIOPathInfo info ) - { - return GetLastWriteTimeUtc( info ).ToLocalTime( ); - } - /// - /// Returns the time of the file or directory was last written - /// - /// Affected file or directory - /// A structure. - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTime( QuickIOFileInfo info ) - { - return GetLastWriteTimeUtc( info.PathInfo ).ToLocalTime( ); - } - - /// - /// Returns the time of the file or directory was last written (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTimeUtc( String path ) - { - return GetLastWriteTimeUtc( new QuickIOPathInfo( path ) ); - } - /// - /// Returns the time of the file or directory was last written (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTimeUtc( QuickIOPathInfo info ) - { - return info.FindData.GetLastWriteTimeUtc( ); - } - /// - /// Returns the time of the file or directory was last written (UTC) - /// - /// Affected file or directory - /// A structure. (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTimeUtc( QuickIOFileInfo info ) - { - return info.FindData.GetLastWriteTimeUtc( ); - } - #endregion - - #region Set All Times - /// - /// Sets the time the file was created. - /// - /// Affected file or directory - /// The time that is to be used - /// The time that is to be used - /// The time that is to be used - public static void SetAllFileTimes( String path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) - { - QuickIOEngine.SetAllFileTimes( QuickIOPath.ToPathUnc(path), creationTime.ToUniversalTime( ), lastAccessTime.ToUniversalTime( ), lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Sets the time the file was created. - /// - /// Affected file or directory - /// The time that is to be used - /// The time that is to be used - /// The time that is to be used - public static void SetAllFileTimes( QuickIOPathInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) - { - QuickIOEngine.SetAllFileTimes( info.FullNameUnc, creationTime.ToUniversalTime( ), lastAccessTime.ToUniversalTime( ), lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Sets the time the file was created. - /// - /// Affected file or directory - /// The time that is to be used - /// The time that is to be used - /// The time that is to be used - public static void SetAllFileTimes( QuickIOFileInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) - { - QuickIOEngine.SetAllFileTimes( info.FullNameUnc, creationTime.ToUniversalTime( ), lastAccessTime.ToUniversalTime( ), lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Sets the dates and times of given directory or file. - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - public static void SetAllFileTimesUtc( String path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetAllFileTimes( QuickIOPath.ToPathUnc( path ), creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ); - } - /// - /// Sets the dates and times of given directory or file. - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - public static void SetAllFileTimesUtc( QuickIOPathInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetAllFileTimes( info.FullNameUnc, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ); - } - /// - /// Sets the dates and times of given directory or file. - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - /// The time that is to be used (UTC) - public static void SetAllFileTimesUtc( QuickIOFileInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetAllFileTimes( info.FullNameUnc, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ); - } - #endregion - - #region Set Creation Time - /// - /// Defines the time at which the file or directory was created - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetCreationTime( String path, DateTime creationTime ) - { - QuickIOEngine.SetCreationTimeUtc( QuickIOPath.ToPathUnc(path), creationTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was created - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetCreationTime( QuickIOPathInfo info, DateTime creationTime ) - { - QuickIOEngine.SetCreationTimeUtc( info.FullNameUnc, creationTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was created - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetCreationTime( QuickIOFileInfo info, DateTime creationTime ) - { - QuickIOEngine.SetCreationTimeUtc( info.FullNameUnc, creationTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was created (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx - public static void SetCreationTimeUtc( String path, DateTime creationTimeUtc ) - { - QuickIOEngine.SetCreationTimeUtc( QuickIOPath.ToPathUnc(path), creationTimeUtc ); - } - /// - /// Defines the time at which the file or directory was created (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx - public static void SetCreationTimeUtc( QuickIOPathInfo info, DateTime creationTimeUtc ) - { - QuickIOEngine.SetCreationTimeUtc( info.FullNameUnc, creationTimeUtc ); - } - /// - /// Defines the time at which the file or directory was created (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx - public static void SetCreationTimeUtc( QuickIOFileInfo info, DateTime creationTimeUtc ) - { - QuickIOEngine.SetCreationTimeUtc( info.FullNameUnc, creationTimeUtc ); - } - #endregion - - #region Set Last Access Time - /// - /// Defines the time at which the file or directory was last accessed - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetLastAccessTime( String path, DateTime lastAccessTime ) - { - QuickIOEngine.SetLastAccessTimeUtc( QuickIOPath.ToPathUnc(path), lastAccessTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last accessed - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx - public static void SetLastAccessTime( QuickIOPathInfo info, DateTime lastAccessTime ) - { - QuickIOEngine.SetLastAccessTimeUtc( info.FullNameUnc, lastAccessTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last accessed - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx - public static void SetLastAccessTime( QuickIOFileInfo info, DateTime lastAccessTime ) - { - QuickIOEngine.SetLastAccessTimeUtc( info.FullNameUnc, lastAccessTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last accessed (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx - public static void SetLastAccessTimeUtc( String path, DateTime lastAccessTimeUtc ) - { - QuickIOEngine.SetLastAccessTimeUtc( QuickIOPath.ToPathUnc(path), lastAccessTimeUtc ); - } - /// - /// Defines the time at which the file or directory was last accessed (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx - public static void SetLastAccessTimeUtc( QuickIOPathInfo info, DateTime lastAccessTimeUtc ) - { - QuickIOEngine.SetLastAccessTimeUtc( info.FullNameUnc, lastAccessTimeUtc ); - } - /// - /// Defines the time at which the file or directory was last accessed (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx - public static void SetLastAccessTimeUtc( QuickIOFileInfo info, DateTime lastAccessTimeUtc ) - { - QuickIOEngine.SetLastAccessTimeUtc( info.FullNameUnc, lastAccessTimeUtc ); - } - #endregion - - #region Set Last Write Time - /// - /// Defines the time at which the file or directory was last written - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetLastWriteTime( String path, DateTime lastWriteTime ) - { - SetLastWriteTimeUtc( path, lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last written - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx - public static void SetLastWriteTime( QuickIOPathInfo info, DateTime lastWriteTime ) - { - SetLastWriteTimeUtc( info, lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last written - /// - /// Affected file or directory - /// The time that is to be used - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx - public static void SetLastWriteTime( QuickIOFileInfo info, DateTime lastWriteTime ) - { - QuickIOEngine.SetLastWriteTimeUtc( info.FullNameUnc, lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last written (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx - public static void SetLastWriteTimeUtc( String path, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetLastWriteTimeUtc( QuickIOPath.ToPathUnc(path), lastWriteTimeUtc ); - } - /// - /// Defines the time at which the file or directory was last written (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx - public static void SetLastWriteTimeUtc( QuickIOPathInfo info, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetLastWriteTimeUtc( info.FullNameUnc, lastWriteTimeUtc ); - } - /// - /// Defines the time at which the file or directory was last written (UTC) - /// - /// Affected file or directory - /// The time that is to be used (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx - public static void SetLastWriteTimeUtc( QuickIOFileInfo info, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetLastWriteTimeUtc( info.FullNameUnc, lastWriteTimeUtc ); - } - #endregion - } -} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.Root.cs b/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.Root.cs deleted file mode 100644 index 1a83071..0000000 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/QuickIOFileTime/QuickIOFile.Root.cs +++ /dev/null @@ -1,50 +0,0 @@ - -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - - -namespace SchwabenCode.QuickIO -{ - public partial class QuickIOFile - { - - #region Root - - /// - /// Returns the root information - /// - /// The path of a file or directory. - /// A QuickIOPathInfo that represents the root or null if is root. - /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx - public static QuickIOPathInfo GetDirectoryRoot( string path ) - { - return GetDirectoryRoot( new QuickIOPathInfo ( path ) ); - } - - /// - /// Returns the root information - /// - /// A file or directory. - /// A QuickIOPathInfo that represents the root or null if is root. - /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx - public static QuickIOPathInfo GetDirectoryRoot( QuickIOPathInfo info ) - { - return new QuickIOPathInfo(info.Root); - } - - /// - /// Returns the root information - /// - /// A file or directory. - /// A QuickIOPathInfo that represents the root or null if is root. - /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx - public static QuickIOPathInfo GetDirectoryRoot( QuickIOFileInfo info ) - { - return new QuickIOPathInfo(info.Root); - } - - #endregion - } -} diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/README.md b/src/SchwabenCode.QuickIO/_CodeGeneration/README.md deleted file mode 100644 index ff2f795..0000000 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/README.md +++ /dev/null @@ -1,12 +0,0 @@ -This project is for code generation only. You cannot use T4 scripts in a Shared Project right now. -https://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/6720163-allow-usiing-t4-template-in-shared-project - -FAQ: -================ -Error: [...]must be either local to this computer or part of your trusted zone. - If you have downloaded this template, you may need to 'Unblock' it using the properties page for the template file in Windows Explorer. - -Solution: -- Download http://technet.microsoft.com/en-us/sysinternals/bb897440.aspx and extract to Windows\System32 Folder -- Run @ cmd: streams -s -d C:\path\to\QuickIO.CodeGeneration -================ \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticAttributeMethods.tt b/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticAttributeMethods.tt deleted file mode 100644 index 61b9386..0000000 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticAttributeMethods.tt +++ /dev/null @@ -1,183 +0,0 @@ -<#+ -void Generate(string className) -{ - - #> -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - - -using System; -using System.IO; -using SchwabenCode.QuickIO.Engine; - -namespace SchwabenCode.QuickIO -{ - public partial class <#= className #> - { - /// - /// Gets the of the directory or file. - /// - /// The path to the directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes( string path , FileAttributes attributes ) - { - QuickIOEngine.SetAttributes( QuickIOPath.ToPathUnc( path ), attributes ); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes( QuickIOPathInfo info, FileAttributes attributes ) - { - QuickIOEngine.SetAttributes( info.FullNameUnc, attributes); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// New attributes to set. - /// The of the directory or file. - public static void SetAttributes( <#= className #>Info info, FileAttributes attributes ) - { - QuickIOEngine.SetAttributes( info.FullNameUnc, attributes); - } - - #region Attributes - /// - /// Gets the of the directory or file. - /// - /// The path to the directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes( string path ) - { - return QuickIOEngine.GetAttributes( QuickIOPath.ToPathUnc (path) ); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes( QuickIOPathInfo info ) - { - return QuickIOEngine.GetAttributes( info.FullNameUnc ); - } - - /// - /// Gets the of the directory or file. - /// - /// A directory or file. - /// The of the directory or file. - public static FileAttributes GetAttributes( <#=className#>Info info ) - { - return QuickIOEngine.GetAttributes(info.FullNameUnc); - } - - #endregion - - #region Remove Attribute - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute( string path, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(QuickIOPath.ToPathUnc(path), attribute, out updatedAttributes); - - return result; - } - - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute( QuickIOPathInfo info, FileAttributes attribute) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - /// - /// Removes the specified attribute from file or directory - /// - /// A directory or file. - /// Attribute to remove - /// true if removed. false if not exists in attributes - public static bool RemoveAttribute( <#=className#>Info info, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryRemoveAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - #endregion - - #region Add Attribute - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute( string path, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(QuickIOPath.ToPathUnc(path), attribute, out updatedAttributes); - - return result; - } - - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute( QuickIOPathInfo info, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - /// - /// Adds the specified attribute to file or directory - /// - /// A directory or file. - /// Attribute to add - /// true if added. false if already exists in attributes - public static bool AddAttribute( <#=className#>Info info, FileAttributes attribute ) - { - FileAttributes updatedAttributes; - bool result = QuickIOEngine.TryAddAttribute(info.FullNameUnc, attribute, out updatedAttributes); - info.Attributes = updatedAttributes; - - return result; - } - - #endregion - } -} -<#+ -} -#> diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticFileTimeMethods.tt b/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticFileTimeMethods.tt deleted file mode 100644 index 45d2cdc..0000000 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticFileTimeMethods.tt +++ /dev/null @@ -1,495 +0,0 @@ -<#+ -void Generate(string className) -{ - -var pathPassValueText = "Affected file or directory"; -var dateTimePassValueText = "The time that is to be used"; -var dateTimeReturnValueText = "A structure."; - - #> -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - - -using System; -using SchwabenCode.QuickIO.Engine; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO -{ - public partial class <#= className #> - { - #region Get Creation Time - /// - /// Returns the creation time of the file or directory - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTime( String path ) - { - return GetCreationTimeUtc( path ).ToLocalTime( ); - } - /// - /// Returns the creation time of the file or directory - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTime( QuickIOPathInfo info ) - { - return GetCreationTimeUtc( info ).ToLocalTime( ); - } - /// - /// Returns the creation time of the file or directory - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTime( <#= className #>Info info ) - { - return GetCreationTimeUtc( info.PathInfo ).ToLocalTime( ); - } - - /// - /// Returns the creation time of the file or directory (UTC) - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTimeUtc( String path ) - { - return GetCreationTimeUtc( new QuickIOPathInfo( path ) ); - } - /// - /// Returns the creation time of the file or directory (UTC) - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTimeUtc( QuickIOPathInfo info ) - { - return info.FindData.GetCreationTimeUtc( ); - } - /// - /// Returns the creation time of the file or directory (UTC) - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetCreationTimeUtc( <#= className #>Info info ) - { - return info.FindData.GetCreationTimeUtc( ); - } - #endregion - - #region Get Last Access Time - /// - /// Returns the time of last access of the file or directory - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTime( String path ) - { - return GetLastAccessTimeUtc( path ).ToLocalTime( ); - } - /// - /// Returns the time of last access of the file or directory - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTime( QuickIOPathInfo info ) - { - return GetLastAccessTimeUtc( info ).ToLocalTime( ); - } - /// - /// Returns the time of last access of the file or directory - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTime( <#= className #>Info info ) - { - return GetLastAccessTimeUtc( info.PathInfo ).ToLocalTime( ); - } - - /// - /// Returns the time of last access of the file or directory (UTC) - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTimeUtc( String path ) - { - return GetLastAccessTimeUtc( new QuickIOPathInfo( path ) ); - } - /// - /// Returns the time of last access of the file or directory (UTC) - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTimeUtc( QuickIOPathInfo info ) - { - return info.FindData.GetLastAccessTimeUtc( ); - } - /// - /// Returns the time of last access of the file or directory (UTC) - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastaccesstimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastAccessTimeUtc( <#= className #>Info info ) - { - return info.FindData.GetLastAccessTimeUtc( ); - } - #endregion - - #region Get Last Write Time - /// - /// Returns the time of the file or directory was last written - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTime( String path ) - { - return GetLastWriteTimeUtc( path ).ToLocalTime( ); - } - /// - /// Returns the time of the file or directory was last written - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTime( QuickIOPathInfo info ) - { - return GetLastWriteTimeUtc( info ).ToLocalTime( ); - } - /// - /// Returns the time of the file or directory was last written - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTime( <#= className #>Info info ) - { - return GetLastWriteTimeUtc( info.PathInfo ).ToLocalTime( ); - } - - /// - /// Returns the time of the file or directory was last written (UTC) - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTimeUtc( String path ) - { - return GetLastWriteTimeUtc( new QuickIOPathInfo( path ) ); - } - /// - /// Returns the time of the file or directory was last written (UTC) - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTimeUtc( QuickIOPathInfo info ) - { - return info.FindData.GetLastWriteTimeUtc( ); - } - /// - /// Returns the time of the file or directory was last written (UTC) - /// - /// <#= pathPassValueText #> - /// <#= dateTimeReturnValueText #> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetimeutc(v=vs.110).aspx - /// No entry found for passed path - public static DateTime GetLastWriteTimeUtc( <#= className #>Info info ) - { - return info.FindData.GetLastWriteTimeUtc( ); - } - #endregion - - #region Set All Times - /// - /// Sets the time the file was created. - /// - /// <#= pathPassValueText #> - /// <#= dateTimePassValueText #> - /// <#= dateTimePassValueText #> - /// <#= dateTimePassValueText #> - public static void SetAllFileTimes( String path, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) - { - QuickIOEngine.SetAllFileTimes( QuickIOPath.ToPathUnc(path), creationTime.ToUniversalTime( ), lastAccessTime.ToUniversalTime( ), lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Sets the time the file was created. - /// - /// <#= pathPassValueText #> - /// <#= dateTimePassValueText #> - /// <#= dateTimePassValueText #> - /// <#= dateTimePassValueText #> - public static void SetAllFileTimes( QuickIOPathInfo info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) - { - QuickIOEngine.SetAllFileTimes( info.FullNameUnc, creationTime.ToUniversalTime( ), lastAccessTime.ToUniversalTime( ), lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Sets the time the file was created. - /// - /// <#= pathPassValueText #> - /// <#= dateTimePassValueText #> - /// <#= dateTimePassValueText #> - /// <#= dateTimePassValueText #> - public static void SetAllFileTimes( <#= className #>Info info, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime ) - { - QuickIOEngine.SetAllFileTimes( info.FullNameUnc, creationTime.ToUniversalTime( ), lastAccessTime.ToUniversalTime( ), lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Sets the dates and times of given directory or file. - /// - /// <#= pathPassValueText #> - /// <#= dateTimePassValueText #> (UTC) - /// <#= dateTimePassValueText #> (UTC) - /// <#= dateTimePassValueText #> (UTC) - public static void SetAllFileTimesUtc( String path, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetAllFileTimes( QuickIOPath.ToPathUnc( path ), creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ); - } - /// - /// Sets the dates and times of given directory or file. - /// - /// <#= pathPassValueText #> - /// <#= dateTimePassValueText #> (UTC) - /// <#= dateTimePassValueText #> (UTC) - /// <#= dateTimePassValueText #> (UTC) - public static void SetAllFileTimesUtc( QuickIOPathInfo info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetAllFileTimes( info.FullNameUnc, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ); - } - /// - /// Sets the dates and times of given directory or file. - /// - /// <#= pathPassValueText #> - /// <#= dateTimePassValueText #> (UTC) - /// <#= dateTimePassValueText #> (UTC) - /// <#= dateTimePassValueText #> (UTC) - public static void SetAllFileTimesUtc( <#= className #>Info info, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetAllFileTimes( info.FullNameUnc, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc ); - } - #endregion - - #region Set Creation Time - /// - /// Defines the time at which the file or directory was created - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetCreationTime( String path, DateTime creationTime ) - { - QuickIOEngine.SetCreationTimeUtc( QuickIOPath.ToPathUnc(path), creationTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was created - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetCreationTime( QuickIOPathInfo info, DateTime creationTime ) - { - QuickIOEngine.SetCreationTimeUtc( info.FullNameUnc, creationTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was created - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetCreationTime( <#= className #>Info info, DateTime creationTime ) - { - QuickIOEngine.SetCreationTimeUtc( info.FullNameUnc, creationTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was created (UTC) - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx - public static void SetCreationTimeUtc( String path, DateTime creationTimeUtc ) - { - QuickIOEngine.SetCreationTimeUtc( QuickIOPath.ToPathUnc(path), creationTimeUtc ); - } - /// - /// Defines the time at which the file or directory was created (UTC) - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx - public static void SetCreationTimeUtc( QuickIOPathInfo info, DateTime creationTimeUtc ) - { - QuickIOEngine.SetCreationTimeUtc( info.FullNameUnc, creationTimeUtc ); - } - /// - /// Defines the time at which the file or directory was created (UTC) - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtimeutc(v=vs.110).aspx - public static void SetCreationTimeUtc( <#= className #>Info info, DateTime creationTimeUtc ) - { - QuickIOEngine.SetCreationTimeUtc( info.FullNameUnc, creationTimeUtc ); - } - #endregion - - #region Set Last Access Time - /// - /// Defines the time at which the file or directory was last accessed - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetLastAccessTime( String path, DateTime lastAccessTime ) - { - QuickIOEngine.SetLastAccessTimeUtc( QuickIOPath.ToPathUnc(path), lastAccessTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last accessed - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx - public static void SetLastAccessTime( QuickIOPathInfo info, DateTime lastAccessTime ) - { - QuickIOEngine.SetLastAccessTimeUtc( info.FullNameUnc, lastAccessTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last accessed - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstime(v=vs.110).aspx - public static void SetLastAccessTime( <#= className #>Info info, DateTime lastAccessTime ) - { - QuickIOEngine.SetLastAccessTimeUtc( info.FullNameUnc, lastAccessTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last accessed (UTC) - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx - public static void SetLastAccessTimeUtc( String path, DateTime lastAccessTimeUtc ) - { - QuickIOEngine.SetLastAccessTimeUtc( QuickIOPath.ToPathUnc(path), lastAccessTimeUtc ); - } - /// - /// Defines the time at which the file or directory was last accessed (UTC) - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx - public static void SetLastAccessTimeUtc( QuickIOPathInfo info, DateTime lastAccessTimeUtc ) - { - QuickIOEngine.SetLastAccessTimeUtc( info.FullNameUnc, lastAccessTimeUtc ); - } - /// - /// Defines the time at which the file or directory was last accessed (UTC) - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastaccesstimeutc(v=vs.110).aspx - public static void SetLastAccessTimeUtc( <#= className #>Info info, DateTime lastAccessTimeUtc ) - { - QuickIOEngine.SetLastAccessTimeUtc( info.FullNameUnc, lastAccessTimeUtc ); - } - #endregion - - #region Set Last Write Time - /// - /// Defines the time at which the file or directory was last written - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> - /// http://msdn.microsoft.com/en-us/library/system.io.file.setcreationtime(v=vs.110).aspx - public static void SetLastWriteTime( String path, DateTime lastWriteTime ) - { - SetLastWriteTimeUtc( path, lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last written - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx - public static void SetLastWriteTime( QuickIOPathInfo info, DateTime lastWriteTime ) - { - SetLastWriteTimeUtc( info, lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last written - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime(v=vs.110).aspx - public static void SetLastWriteTime( <#= className #>Info info, DateTime lastWriteTime ) - { - QuickIOEngine.SetLastWriteTimeUtc( info.FullNameUnc, lastWriteTime.ToUniversalTime( ) ); - } - /// - /// Defines the time at which the file or directory was last written (UTC) - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx - public static void SetLastWriteTimeUtc( String path, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetLastWriteTimeUtc( QuickIOPath.ToPathUnc(path), lastWriteTimeUtc ); - } - /// - /// Defines the time at which the file or directory was last written (UTC) - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx - public static void SetLastWriteTimeUtc( QuickIOPathInfo info, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetLastWriteTimeUtc( info.FullNameUnc, lastWriteTimeUtc ); - } - /// - /// Defines the time at which the file or directory was last written (UTC) - /// - /// <#= pathPassValueText #> - /// <#=dateTimePassValueText#> (UTC) - /// http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetimeutc(v=vs.110).aspx - public static void SetLastWriteTimeUtc( <#= className #>Info info, DateTime lastWriteTimeUtc ) - { - QuickIOEngine.SetLastWriteTimeUtc( info.FullNameUnc, lastWriteTimeUtc ); - } - #endregion - } -} -<#+ - } -#> diff --git a/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticRootMethods.tt b/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticRootMethods.tt deleted file mode 100644 index e6a2336..0000000 --- a/src/SchwabenCode.QuickIO/_CodeGeneration/Templates/StaticRootMethods.tt +++ /dev/null @@ -1,57 +0,0 @@ -<#+ -void Generate(string className) -{ - - #> -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - - -namespace SchwabenCode.QuickIO -{ - public partial class <#= className #> - { - - #region Root - - /// - /// Returns the root information - /// - /// The path of a file or directory. - /// A QuickIOPathInfo that represents the root or null if is root. - /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx - public static QuickIOPathInfo GetDirectoryRoot( string path ) - { - return GetDirectoryRoot( new QuickIOPathInfo ( path ) ); - } - - /// - /// Returns the root information - /// - /// A file or directory. - /// A QuickIOPathInfo that represents the root or null if is root. - /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx - public static QuickIOPathInfo GetDirectoryRoot( QuickIOPathInfo info ) - { - return new QuickIOPathInfo(info.Root); - } - - /// - /// Returns the root information - /// - /// A file or directory. - /// A QuickIOPathInfo that represents the root or null if is root. - /// http://msdn.microsoft.com/en-us/library/system.io.directory.getdirectoryroot(v=vs.110).aspx - public static QuickIOPathInfo GetDirectoryRoot( <#= className #>Info info ) - { - return new QuickIOPathInfo(info.Root); - } - - #endregion - } -} -<#+ -} -#> diff --git a/src/SchwabenCode.QuickIO/_CurrentlyUnused/QuickIOShareDetailedInfo.cs b/src/SchwabenCode.QuickIO/_CurrentlyUnused/QuickIOShareDetailedInfo.cs deleted file mode 100644 index b398aa3..0000000 --- a/src/SchwabenCode.QuickIO/_CurrentlyUnused/QuickIOShareDetailedInfo.cs +++ /dev/null @@ -1,95 +0,0 @@ -//// -//// Copyright (c) 2014 PathMatchAll Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -//// -//// Benjamin Abt -//// 06/04/2014 -//// QuickIOShareDetailedInfo -//using System; -//using System.Diagnostics.Contracts; - -//namespace SchwabenCode.QuickIO.Win32 -//{ -// /// -// /// Container of detailed share information -// /// -// public class QuickIOShareDetailedInfo -// { -// /// -// /// Transfers the struct information to the class -// /// -// /// share information -// internal QuickIOShareDetailedInfo( Win32ApiShareInfoAdmin shareInfo ) -// { -// Contract.Requires( shareInfo != null ); - -// this.Name = shareInfo.ShareName; -// this.Type = shareInfo.ShareType; -// this.Remark = shareInfo.Remark; - -// this.Permissions = shareInfo.Permissions; -// this.MaxUsers = shareInfo.MaxUsers; -// this.CurrentUsers = shareInfo.CurrentUsers; -// this.Path = shareInfo.Path; -// this.Password = shareInfo.Password; -// } - -// /// -// /// Transfers the struct information to the class -// /// -// /// share information -// internal QuickIOShareDetailedInfo( Win32ApiShareInfoNormal shareInfo ) -// { -// this.Name = shareInfo.ShareName; -// this.Type = shareInfo.ShareType; -// this.Remark = shareInfo.Remark; -// } - -// #region Required - -// /// -// /// Name of Share -// /// -// public String Name { get; private set; } - -// /// -// /// Share Type -// /// -// public QuickIOShareType Type { get; private set; } - -// /// -// /// Remark / Comment -// /// -// public String Remark { get; private set; } - -// #endregion - -// #region Optional - -// /// -// /// Permissions. Is null, if admin privileges are not granted. -// /// -// public Int32? Permissions { get; private set; } - -// /// -// /// MaxUsers of the parallel connected users. Is null, if admin privileges are not granted. -// /// -// public Int32? MaxUsers { get; private set; } - -// /// -// /// CurrentUsers connected to the share. Is null, if admin privileges are not granted. -// /// -// public Int32? CurrentUsers { get; private set; } - -// /// -// /// Permissions. Is null, if admin privileges are not granted. -// /// -// public String Path { get; private set; } - -// /// -// /// Password. Is null, if admin privileges are not granted. -// /// -// public String Password { get; private set; } - -// #endregion -// } -//} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/_Enums/QuickIOEnumerateOptions.cs b/src/SchwabenCode.QuickIO/_Enums/QuickIOEnumerateOptions.cs deleted file mode 100644 index 1d4f903..0000000 --- a/src/SchwabenCode.QuickIO/_Enums/QuickIOEnumerateOptions.cs +++ /dev/null @@ -1,26 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; - -namespace SchwabenCode.QuickIO -{ - /// - /// Options for enumerations - /// - [Flags] - public enum QuickIOEnumerateOptions - { - /// - /// No options - /// - None, - /// - /// Suppresses all exceptions - /// - SuppressAllExceptions - - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/_Enums/QuickIOFileCompareCriteria.cs b/src/SchwabenCode.QuickIO/_Enums/QuickIOFileCompareCriteria.cs deleted file mode 100644 index 02ec95a..0000000 --- a/src/SchwabenCode.QuickIO/_Enums/QuickIOFileCompareCriteria.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; - -namespace SchwabenCode.QuickIO -{ - /// - /// Options for file compare. You can select multiple flags or use for all options - /// - [Flags] - public enum QuickIOFileCompareCriteria - { - /// - /// PathMatchAll options will be verified - /// - All = 0, - - /// - /// Compares all timestamps - /// - TimestampsAll, - - /// - /// Compares timestamp of file creation - /// - TimestampCreated, - - /// - /// Compares timestamp of file last written to - /// - TimestampLastWritten, - - /// - /// Compares timestamp of file last accessed to - /// - TimestampLastAccessed, - - /// - /// Compares length of file (without checking the content!) - /// - ByteLength, - - /// - /// Compares the contents. Requires read access. - /// - Content - } -} diff --git a/src/SchwabenCode.QuickIO/_Enums/QuickIOFileSystemEntryType.cs b/src/SchwabenCode.QuickIO/_Enums/QuickIOFileSystemEntryType.cs deleted file mode 100644 index a6ae956..0000000 --- a/src/SchwabenCode.QuickIO/_Enums/QuickIOFileSystemEntryType.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -namespace SchwabenCode.QuickIO -{ - /// - /// Represents type of path or handle - /// - public enum QuickIOFileSystemEntryType - { - /// - /// Represents a file ( does not contain directory flag) - /// - File = 0, - - /// - /// Represents a directory (contains directory flag) - /// - Directory = 1 - } -} diff --git a/src/SchwabenCode.QuickIO/_Enums/QuickIOPathLocation.cs b/src/SchwabenCode.QuickIO/_Enums/QuickIOPathLocation.cs deleted file mode 100644 index 110c2c0..0000000 --- a/src/SchwabenCode.QuickIO/_Enums/QuickIOPathLocation.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -namespace SchwabenCode.QuickIO -{ - /// - /// Path Location (Local, QuickIOShareInfo) - /// - /// http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx - public enum QuickIOPathLocation - { - /// - /// Represents Local Path - /// - Local, - /// - /// Represents Network QuickIOShareInfo - /// - Share - } -} diff --git a/src/SchwabenCode.QuickIO/_Enums/QuickIOPathType.cs b/src/SchwabenCode.QuickIO/_Enums/QuickIOPathType.cs deleted file mode 100644 index f54da6a..0000000 --- a/src/SchwabenCode.QuickIO/_Enums/QuickIOPathType.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -namespace SchwabenCode.QuickIO -{ - /// - /// Path Types (Regular or UNC ) - /// - /// http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx - public enum QuickIOPathType - { - /// - /// Regular - /// - Regular, - /// - /// UNC - /// - UNC - } -} diff --git a/src/SchwabenCode.QuickIO/_Enums/QuickIOShareApiReadLevel.cs b/src/SchwabenCode.QuickIO/_Enums/QuickIOShareApiReadLevel.cs deleted file mode 100644 index 34d40c9..0000000 --- a/src/SchwabenCode.QuickIO/_Enums/QuickIOShareApiReadLevel.cs +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -namespace SchwabenCode.QuickIO -{ - /// - /// Read level indicator for share access - /// - public enum QuickIOShareApiReadLevel : int - { - /// - /// Requests all information and required admin privilegs - /// - Admin = 2, - /// - /// Default call type - /// - Normal = 1 - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/_Enums/QuickIOShareType.cs b/src/SchwabenCode.QuickIO/_Enums/QuickIOShareType.cs deleted file mode 100644 index c7194c8..0000000 --- a/src/SchwabenCode.QuickIO/_Enums/QuickIOShareType.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -namespace SchwabenCode.QuickIO -{ - /// - /// Enum collection of available shares types - /// - public enum QuickIOShareType : uint - { - /// - /// Disk or network share share - /// - Disk = 0, - - /// - /// Printer share - /// - Printer = 1, - - /// - /// Device share - /// - Device = 2, - - /// - /// IPC share - IPC = 2147483651, - - /// - /// Special share - /// - Special = 2147483648 - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/_Exceptions/DirectoryAlreadyExistsException.cs b/src/SchwabenCode.QuickIO/_Exceptions/DirectoryAlreadyExistsException.cs deleted file mode 100644 index 0f838d1..0000000 --- a/src/SchwabenCode.QuickIO/_Exceptions/DirectoryAlreadyExistsException.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - /// - /// This error is raised if you want to create for example a folder which already exists. - /// - public class DirectoryAlreadyExistsException : QuickIOBaseException - { - /// - /// Creates an instance of - /// - /// Error message - /// Affected directory path - public DirectoryAlreadyExistsException( string message, string path ) - : base( message, path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( message ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - } - } -} diff --git a/src/SchwabenCode.QuickIO/_Exceptions/DirectoryNotEmptyException.cs b/src/SchwabenCode.QuickIO/_Exceptions/DirectoryNotEmptyException.cs deleted file mode 100644 index 7144d2d..0000000 --- a/src/SchwabenCode.QuickIO/_Exceptions/DirectoryNotEmptyException.cs +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - /// - /// This error is raised if a folder that is not empty should be deleted. - /// - public class DirectoryNotEmptyException : QuickIOBaseException - { - /// - /// Creates an instance of - /// - /// Error message - /// Affected directory path - public DirectoryNotEmptyException( string message, string path ) - : base( message, path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( message ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/_Exceptions/FileAlreadyExistsException.cs b/src/SchwabenCode.QuickIO/_Exceptions/FileAlreadyExistsException.cs deleted file mode 100644 index 96b8aa7..0000000 --- a/src/SchwabenCode.QuickIO/_Exceptions/FileAlreadyExistsException.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - /// - /// This error is raised if a file should be created that already exists. - /// - public class FileAlreadyExistsException : QuickIOBaseException - { - /// - /// Creates an instance of - /// - /// Affected file path - public FileAlreadyExistsException( string path ) - : base( "Cannot create a file when that file already exists.", path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - } - - /// - /// Creates an instance of - /// - /// Error message - /// Affected file path - public FileAlreadyExistsException( string message, string path ) - : base( message, path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( message ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - } - } -} - diff --git a/src/SchwabenCode.QuickIO/_Exceptions/FileSystemIsBusyException.cs b/src/SchwabenCode.QuickIO/_Exceptions/FileSystemIsBusyException.cs deleted file mode 100644 index 693ef8f..0000000 --- a/src/SchwabenCode.QuickIO/_Exceptions/FileSystemIsBusyException.cs +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - /// - /// This error is raised if file system is busy and further operations are not able to execute - /// - public class FileSystemIsBusyException : QuickIOBaseException - { - /// - /// Creates an instance of - /// - /// Error message - /// Affected directory path - public FileSystemIsBusyException(string message, string path) - : base(message, path) - { - Contract.Requires(!String.IsNullOrWhiteSpace(message)); - Contract.Requires(!String.IsNullOrWhiteSpace(path)); - } - } -} diff --git a/src/SchwabenCode.QuickIO/_Exceptions/InvalidPathException.cs b/src/SchwabenCode.QuickIO/_Exceptions/InvalidPathException.cs deleted file mode 100644 index 4df6379..0000000 --- a/src/SchwabenCode.QuickIO/_Exceptions/InvalidPathException.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - /// - /// Invalid Path Exception - /// - public class InvalidPathException : QuickIOBaseException - { - /// - /// Invalid Path Exception - /// - /// Invalid Path - public InvalidPathException( string path ) - : base( "The filename, directory name, or volume label syntax is incorrect.", path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - } - /// - /// Invalid Path Exception - /// - /// Error Message - /// Invalid Path - public InvalidPathException( string message, string path ) - : base( message, path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( message ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/_Exceptions/PathAlreadyExistsException.cs b/src/SchwabenCode.QuickIO/_Exceptions/PathAlreadyExistsException.cs deleted file mode 100644 index ee76935..0000000 --- a/src/SchwabenCode.QuickIO/_Exceptions/PathAlreadyExistsException.cs +++ /dev/null @@ -1,26 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - /// - /// Exception if path does not exist. - /// - public class PathAlreadyExistsException : QuickIOBaseException - { - /// - /// Exception if path does not exist. - /// - public PathAlreadyExistsException( string message, string path ) - : base( message, path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( message ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/_Exceptions/PathNotFoundException.cs b/src/SchwabenCode.QuickIO/_Exceptions/PathNotFoundException.cs deleted file mode 100644 index 67eca5e..0000000 --- a/src/SchwabenCode.QuickIO/_Exceptions/PathNotFoundException.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - /// - /// Exception if path does not exist. - /// - public class PathNotFoundException : QuickIOBaseException - { - /// - /// Exception if path does not exist. - /// - public PathNotFoundException( string path ) - : this( $"The system cannot find the path specified", path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - } - - /// - /// Exception if path does not exist. - /// - public PathNotFoundException( string message, string path ) - : base( message, path ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( message ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - } - } -} diff --git a/src/SchwabenCode.QuickIO/_Exceptions/QuickIOBaseException.cs b/src/SchwabenCode.QuickIO/_Exceptions/QuickIOBaseException.cs deleted file mode 100644 index d7248bf..0000000 --- a/src/SchwabenCode.QuickIO/_Exceptions/QuickIOBaseException.cs +++ /dev/null @@ -1,46 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; -using System.ComponentModel; -using System.Diagnostics.Contracts; - -namespace SchwabenCode.QuickIO -{ - /// - /// Abstract base class for exceptions - /// - [EditorBrowsable( EditorBrowsableState.Never )] - public abstract class QuickIOBaseException : Exception - { - /// - /// Affected Path - /// - public string Path { get; private set; } - - /// - /// Abstract base class for exceptions - /// - protected QuickIOBaseException( String message, string path ) - : base( message ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( message ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - this.Path = path; - } - - /// - /// Abstract base class for exceptions - /// - protected QuickIOBaseException( String message, string path, Exception innerException ) - : base( message, innerException ) - { - Contract.Requires( !String.IsNullOrWhiteSpace( message ) ); - Contract.Requires( !String.IsNullOrWhiteSpace( path ) ); - - this.Path = path; - } - } -} \ No newline at end of file diff --git a/src/SchwabenCode.QuickIO/_Exceptions/QuickIOTransferAlreadyRunningException.cs b/src/SchwabenCode.QuickIO/_Exceptions/QuickIOTransferAlreadyRunningException.cs deleted file mode 100644 index 6371725..0000000 --- a/src/SchwabenCode.QuickIO/_Exceptions/QuickIOTransferAlreadyRunningException.cs +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; - -namespace SchwabenCode.QuickIO -{ - /// - /// Exception of already running transfer activity - /// - public class QuickIOTransferAlreadyRunningException : Exception - { - /// - /// Creates a new exception of - /// - /// The error message - public QuickIOTransferAlreadyRunningException( string message ) : base( message ) - { - - } - } -} diff --git a/src/SchwabenCode.QuickIO/_Exceptions/UnmatchedFileSystemEntryTypeException.cs b/src/SchwabenCode.QuickIO/_Exceptions/UnmatchedFileSystemEntryTypeException.cs deleted file mode 100644 index f5a1557..0000000 --- a/src/SchwabenCode.QuickIO/_Exceptions/UnmatchedFileSystemEntryTypeException.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; - -namespace SchwabenCode.QuickIO -{ - /// - /// Exception if path returns another type as excepted - /// - public sealed class UnmatchedFileSystemEntryTypeException : Exception - { - /// - /// Expected Type - /// - public QuickIOFileSystemEntryType Expected { get; private set; } - - /// - /// Type found - /// - public QuickIOFileSystemEntryType Found { get; private set; } - - /// - /// Affected full path - /// - public string Path { get; private set; } - - /// - /// Exception if path returns another type as excepted - /// - public UnmatchedFileSystemEntryTypeException( QuickIOFileSystemEntryType expected, QuickIOFileSystemEntryType found, string path ) - : base( "FileSystemEntryType not matched!" ) - { - Expected = expected; - Found = found; - Path = path; - } - } -} diff --git a/src/SchwabenCode.QuickIO/_Exceptions/UnsupportedDriveTypeException.cs b/src/SchwabenCode.QuickIO/_Exceptions/UnsupportedDriveTypeException.cs deleted file mode 100644 index 1b218dc..0000000 --- a/src/SchwabenCode.QuickIO/_Exceptions/UnsupportedDriveTypeException.cs +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -namespace SchwabenCode.QuickIO -{ - /// - /// Represents an exception for unsuuported drive types - /// - public class UnsupportedDriveTypeException : QuickIOBaseException - { - /// - /// Creates an instance of - /// - /// Unsupported drive - public UnsupportedDriveTypeException( string path ) - : base( "Unsupported Drive Type: only logical drives are supported; do not use mapped network drives.", path ) - { - } - } -} diff --git a/src/SchwabenCode.QuickIO/_Exceptions/UnsupportedShareTypeException.cs b/src/SchwabenCode.QuickIO/_Exceptions/UnsupportedShareTypeException.cs deleted file mode 100644 index 14b7a48..0000000 --- a/src/SchwabenCode.QuickIO/_Exceptions/UnsupportedShareTypeException.cs +++ /dev/null @@ -1,25 +0,0 @@ -// -// Copyright (c) 2016 Benjamin Abt Rights Reserved - DO NOT REMOVE OR EDIT COPYRIGHT -// -// Benjamin Abt - -using System; - -namespace SchwabenCode.QuickIO -{ - /// - /// Represents an exception for unsuuported drive types - /// - public class UnsupportedShareTypeException : QuickIOBaseException - { - /// - /// Creates an instance of - /// - /// Unsupported drive - /// Error - public UnsupportedShareTypeException( String message, string path ) - : base( message, path ) - { - } - } -} \ No newline at end of file diff --git a/test/SchwabenCode.QuickIO.IntegrationTests/IntegrationTestBase.cs b/test/SchwabenCode.QuickIO.IntegrationTests/IntegrationTestBase.cs deleted file mode 100644 index 92a8812..0000000 --- a/test/SchwabenCode.QuickIO.IntegrationTests/IntegrationTestBase.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace SchwabenCode.QuickIO.IntegrationTests -{ - public abstract class IntegrationTestBase - { - public static string CurrentPath() - { - return System.AppContext.BaseDirectory; - } - } -} diff --git a/test/SchwabenCode.QuickIO.IntegrationTests/Properties/AssemblyInfo.cs b/test/SchwabenCode.QuickIO.IntegrationTests/Properties/AssemblyInfo.cs deleted file mode 100644 index b985176..0000000 --- a/test/SchwabenCode.QuickIO.IntegrationTests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("SchwabenCode.QuickIO.IntegrationTests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("SchwabenCode.QuickIO.IntegrationTests")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("84664f86-61b1-4970-b390-4fcd71a8c081")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/test/SchwabenCode.QuickIO.IntegrationTests/QuickIODirectoryInfo_Enumerations.cs b/test/SchwabenCode.QuickIO.IntegrationTests/QuickIODirectoryInfo_Enumerations.cs deleted file mode 100644 index aac7329..0000000 --- a/test/SchwabenCode.QuickIO.IntegrationTests/QuickIODirectoryInfo_Enumerations.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; -using FluentAssertions; -using Xunit; - -namespace SchwabenCode.QuickIO.IntegrationTests -{ - public class QuickIODirectoryInfo_Enumerations : IntegrationTestBase - { - [Theory] - [InlineData( true, @"_TestFolders\ExistingFolder", "*.txt", 1 )] - //[InlineData( "_TestFolders/ExistingFolder", "*.txt", 1 )] - //[InlineData( "_TestFolders/ExistingFolder", "*.TXT", 1 )] - public void QuickIODirectoryInfo_EnumerateFilesCount( bool isRelative, string path, string pattern, int expected ) - { - if( isRelative ) - { - path = QuickIOPath.Combine( CurrentPath(), path ); - } - - QuickIODirectoryInfo directoryInfo = new QuickIODirectoryInfo( path ); - IEnumerable result = ( pattern == null ? directoryInfo.EnumerateFiles() : directoryInfo.EnumerateFiles( pattern ) ); - - List list = result.ToList(); - list.Count.Should().Be( expected ); - } - } -} diff --git a/test/SchwabenCode.QuickIO.IntegrationTests/QuickIOPathInfoTests.cs b/test/SchwabenCode.QuickIO.IntegrationTests/QuickIOPathInfoTests.cs deleted file mode 100644 index 2ee602f..0000000 --- a/test/SchwabenCode.QuickIO.IntegrationTests/QuickIOPathInfoTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.IO; -using FluentAssertions; -using Xunit; - -namespace SchwabenCode.QuickIO.IntegrationTests -{ - public class QuickIOPathInfoTests : IntegrationTestBase - { - [Fact] - public void QuickIOPathInfoFile() - { - string parent = QuickIOPath.Combine(CurrentPath(), "_TestFiles"); - string fullpath = QuickIOPath.Combine(CurrentPath(), "_TestFiles", "ExistingTestFile.txt"); - string fullPathUnc = QuickIOPath.ToPathUnc(fullpath); - string root = QuickIOPath.GetPathRoot(fullpath); - - QuickIOPathInfo pi = new QuickIOPathInfo(fullpath); - - pi.Should().NotBe(null); - - pi.Name.Should().Be("ExistingTestFile.txt"); - pi.FullName.Should().Be(fullpath); - pi.FullNameUnc.Should().Be(fullPathUnc); - pi.Parent.Should().Be(parent); - pi.Root.Should().Be(root); - pi.IsRoot.Should().Be(false); - pi.FindData.Should().NotBe(null); - pi.Attributes.Contains(FileAttributes.Directory).Should().Be(false); - pi.Exists.Should().Be(true); - pi.SystemEntryType.Should().Be(QuickIOFileSystemEntryType.File); - - - } - } -} diff --git a/test/SchwabenCode.QuickIO.IntegrationTests/SchwabenCode.QuickIO.IntegrationTests.csproj b/test/SchwabenCode.QuickIO.IntegrationTests/SchwabenCode.QuickIO.IntegrationTests.csproj deleted file mode 100644 index 82622ee..0000000 --- a/test/SchwabenCode.QuickIO.IntegrationTests/SchwabenCode.QuickIO.IntegrationTests.csproj +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - Debug - AnyCPU - {84664F86-61B1-4970-B390-4FCD71A8C081} - Library - Properties - SchwabenCode.QuickIO.IntegrationTests - SchwabenCode.QuickIO.IntegrationTests - v4.6 - 512 - - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\packages\FluentAssertions.4.14.0\lib\net45\FluentAssertions.dll - True - - - ..\..\packages\FluentAssertions.4.14.0\lib\net45\FluentAssertions.Core.dll - True - - - - - - - - - - - ..\..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll - True - - - ..\..\packages\xunit.assert.2.1.0\lib\dotnet\xunit.assert.dll - True - - - ..\..\packages\xunit.extensibility.core.2.1.0\lib\dotnet\xunit.core.dll - True - - - ..\..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll - True - - - - - - - - - - - - - - Always - - - Always - - - - - {b33dbcee-42f4-4570-b4ef-5412ce4a4bda} - SchwabenCode.QuickIO - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - \ No newline at end of file diff --git a/test/SchwabenCode.QuickIO.IntegrationTests/_TestFiles/ExistingTestFile.txt b/test/SchwabenCode.QuickIO.IntegrationTests/_TestFiles/ExistingTestFile.txt deleted file mode 100644 index d928dda..0000000 --- a/test/SchwabenCode.QuickIO.IntegrationTests/_TestFiles/ExistingTestFile.txt +++ /dev/null @@ -1 +0,0 @@ -AAAAA \ No newline at end of file diff --git a/test/SchwabenCode.QuickIO.IntegrationTests/packages.config b/test/SchwabenCode.QuickIO.IntegrationTests/packages.config deleted file mode 100644 index 7eb1ec5..0000000 --- a/test/SchwabenCode.QuickIO.IntegrationTests/packages.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/SchwabenCode.QuickIO.UnitTests/ExceptionTests.cs b/test/SchwabenCode.QuickIO.UnitTests/ExceptionTests.cs deleted file mode 100644 index 69efa2a..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/ExceptionTests.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System; -using FluentAssertions; -using SchwabenCode.QuickIO.UnitTests.TestClasses; -using Xunit; - -namespace SchwabenCode.QuickIO.UnitTests -{ - public class ExceptionTests - { - [Fact] - public void DirectoryAlreadyExistsExceptionCtor() - { - DirectoryAlreadyExistsException ex = new DirectoryAlreadyExistsException( "message", "path" ); - ex.Message.Should().Be( "message" ); - ex.Path.Should().Be( "path" ); - } - - [Fact] - public void DirectoryNotEmptyExceptionCtor() - { - DirectoryNotEmptyException ex = new DirectoryNotEmptyException( "message", "path" ); - ex.Message.Should().Be( "message" ); - ex.Path.Should().Be( "path" ); - } - - [Fact] - public void FileAlreadyExistsExceptionCtor1() - { - FileAlreadyExistsException ex = new FileAlreadyExistsException( "message", "path" ); - ex.Message.Should().Be( "message" ); - ex.Path.Should().Be( "path" ); - } - - [Fact] - public void FileAlreadyExistsExceptionCtor2() - { - FileAlreadyExistsException ex = new FileAlreadyExistsException( "path" ); - ex.Message.Should().Be( "Cannot create a file when that file already exists." ); - ex.Path.Should().Be( "path" ); - } - - [Fact] - public void FileSystemIsBusyExceptionCtor() - { - FileSystemIsBusyException ex = new FileSystemIsBusyException( "message", "path" ); - ex.Message.Should().Be( "message" ); - ex.Path.Should().Be( "path" ); - } - - [Fact] - public void InvalidPathExceptionCtor1() - { - InvalidPathException ex = new InvalidPathException( "message", "path" ); - ex.Message.Should().Be( "message" ); - ex.Path.Should().Be( "path" ); - } - - [Fact] - public void InvalidPathExceptionCtor2() - { - InvalidPathException ex = new InvalidPathException( "path" ); - ex.Message.Should().Be( "The filename, directory name, or volume label syntax is incorrect." ); - ex.Path.Should().Be( "path" ); - } - - [Fact] - public void PathAlreadyExistsExceptionCtor1() - { - PathAlreadyExistsException ex = new PathAlreadyExistsException( "message", "path" ); - ex.Message.Should().Be( "message" ); - ex.Path.Should().Be( "path" ); - } - - [Fact] - public void PathNotFoundExceptionCtor1() - { - PathNotFoundException ex = new PathNotFoundException( "message", "path" ); - ex.Message.Should().Be( "message" ); - ex.Path.Should().Be( "path" ); - } - - [Fact] - public void PathNotFoundExceptionCtor2() - { - PathNotFoundException ex = new PathNotFoundException( "path" ); - ex.Message.Should().Be( "The system cannot find the path specified" ); - ex.Path.Should().Be( "path" ); - } - - [ Fact ] - public void QuickIOBaseExceptionCtor1() - { - QuickIOBaseException ex = new TestExceptionClass( "message", "path" ); - ex.Message.Should().Be( "message" ); - ex.Path.Should().Be( "path" ); - } - - [Fact] - public void QuickIOBaseExceptionCtor2() - { - Exception inner = new Exception( "InnerExMessage" ); - - QuickIOBaseException ex = new TestExceptionClass( "message", "path", inner ); - ex.Message.Should().Be( "message" ); - ex.Path.Should().Be( "path" ); - ex.InnerException.Should().Be( inner ); - } - - [Fact] - public void QuickIOTransferAlreadyRunningExceptionCtor1() - { - QuickIOTransferAlreadyRunningException ex = new QuickIOTransferAlreadyRunningException( "message" ); - ex.Message.Should().Be( "message" ); - } - - [Fact] - public void UnmatchedFileSystemEntryTypeExceptionCtor1() - { - UnmatchedFileSystemEntryTypeException ex = new UnmatchedFileSystemEntryTypeException( QuickIOFileSystemEntryType.Directory, QuickIOFileSystemEntryType.Directory, "path" ); - ex.Message.Should().Be( "FileSystemEntryType not matched!" ); - ex.Expected.Should().Be( QuickIOFileSystemEntryType.Directory ); - ex.Found.Should().Be( QuickIOFileSystemEntryType.Directory ); - ex.Path.Should().Be( "path" ); - } - - [Fact] - public void UnsupportedDriveTypeExceptionCtor1() - { - UnsupportedDriveTypeException ex = new UnsupportedDriveTypeException( "path" ); - ex.Message.Should().Be( "Unsupported Drive Type: only logical drives are supported; do not use mapped network drives." ); - ex.Path.Should().Be( "path" ); - } - - [Fact] - public void UnsupportedShareTypeExceptionCtor1() - { - UnsupportedShareTypeException ex = new UnsupportedShareTypeException( "message", "path" ); - ex.Message.Should().Be( "message" ); - ex.Path.Should().Be( "path" ); - } - } -} \ No newline at end of file diff --git a/test/SchwabenCode.QuickIO.UnitTests/FileAttributesExtensionsTests.cs b/test/SchwabenCode.QuickIO.UnitTests/FileAttributesExtensionsTests.cs deleted file mode 100644 index c2cb6ed..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/FileAttributesExtensionsTests.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.IO; -using FluentAssertions; -using Xunit; - -namespace SchwabenCode.QuickIO.UnitTests -{ - public class FileAttributesExtensionsTests - { - - [Fact] - public void AddFileAttrribute() - { - FileAttributes attr = FileAttributes.Archive; - - FileAttributes result = attr.Add(FileAttributes.System); - - result.Contains(FileAttributes.Archive).Should().Be(true); - result.Contains(FileAttributes.System).Should().Be(true); - } - - [Fact] - public void ContainsFileAttrribute() - { - FileAttributes attr = FileAttributes.Archive | FileAttributes.System | FileAttributes.ReadOnly; - - attr.Contains(FileAttributes.ReadOnly).Should().BeTrue(); - attr.Contains(FileAttributes.Directory).Should().BeFalse(); - } - - [Fact] - public void RemoveFileAttribute() - { - FileAttributes attr = FileAttributes.Archive | FileAttributes.System; - - FileAttributes result = attr.Remove(FileAttributes.Archive); - - result.Contains(FileAttributes.Archive).Should().Be(false); - result.Contains(FileAttributes.System).Should().Be(true); - } - - [Fact] - public void ContainsFileAttribute() - { - FileAttributes attr = FileAttributes.Archive; - - attr.Contains(FileAttributes.Archive).Should().Be(true); - attr.Contains(FileAttributes.System).Should().Be(false); - } - } -} diff --git a/test/SchwabenCode.QuickIO.UnitTests/Properties/AssemblyInfo.cs b/test/SchwabenCode.QuickIO.UnitTests/Properties/AssemblyInfo.cs deleted file mode 100644 index 3236af4..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("SchwabenCode.QuickIO.UnitTests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("SchwabenCode.QuickIO.UnitTests")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("4867dd64-c401-4139-84f7-4252e138cc9b")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/test/SchwabenCode.QuickIO.UnitTests/QuickIODiskInformationTests.cs b/test/SchwabenCode.QuickIO.UnitTests/QuickIODiskInformationTests.cs deleted file mode 100644 index fd132f2..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/QuickIODiskInformationTests.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using FluentAssertions; - -namespace SchwabenCode.QuickIO.UnitTests -{ - public class QuickIODiskInformationTests - { - public void QuickIODiskInformationCtor() - { - QuickIODiskInformation di = new QuickIODiskInformation( 1, 2, 3 ); - - di.Should().NotBeNull(); - di.FreeBytes.Should().Be( 1 ); - di.TotalBytes.Should().Be( 2 ); - di.TotalFreeBytes.Should().Be( 3 ); - } - } -} diff --git a/test/SchwabenCode.QuickIO.UnitTests/QuickIOFileChunkTests.cs b/test/SchwabenCode.QuickIO.UnitTests/QuickIOFileChunkTests.cs deleted file mode 100644 index bdebbd8..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/QuickIOFileChunkTests.cs +++ /dev/null @@ -1,39 +0,0 @@ -using FluentAssertions; -using Xunit; - -namespace SchwabenCode.QuickIO.UnitTests -{ - public class QuickIOFileChunkTests - { - [Fact] - public void QuickIOFileChunkEqualTests() - { - var position = 1; - byte[ ] bytes = new byte[ 10 ]; - - QuickIOFileChunk chunk = new QuickIOFileChunk( 1, bytes ); - chunk.Position.Should().Be( 1 ); - chunk.Bytes.Should().Equal( bytes ); - - QuickIOFileChunk sameChunk = new QuickIOFileChunk( 1, bytes ); - sameChunk.Position.Should().Be( 1 ); - sameChunk.Bytes.Should().Equal( bytes ); - - chunk.PositionEquals( sameChunk ).Should().Be( true ); - chunk.BytesEquals( sameChunk ).Should().Be( true ); - chunk.ChunkEquals( sameChunk ).Should().Be( true ); - chunk.Equals( sameChunk ).Should().Be( false ); - - byte[ ] otherBytes = new byte[ 5 ]; - QuickIOFileChunk otherChunk = new QuickIOFileChunk( 2, otherBytes ); - otherChunk.Position.Should().Be( 2 ); - otherChunk.Bytes.Should().Equal( otherBytes ); - - chunk.PositionEquals( otherChunk ).Should().Be( false ); - chunk.BytesEquals( otherChunk ).Should().Be( false ); - chunk.ChunkEquals( otherChunk ).Should().Be( false ); - chunk.Equals( otherChunk ).Should().Be( false ); - - } - } -} diff --git a/test/SchwabenCode.QuickIO.UnitTests/QuickIOFileMetadataTests.cs b/test/SchwabenCode.QuickIO.UnitTests/QuickIOFileMetadataTests.cs deleted file mode 100644 index 3affc3a..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/QuickIOFileMetadataTests.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using FluentAssertions; -using Xunit; - -namespace SchwabenCode.QuickIO.UnitTests -{ - public class QuickIOFileMetadataTests - { - [Fact] - public void QuickIOFileMetadataInstance() - { - Win32FindDataTestValue data = new Win32FindDataTestValue(); - - QuickIOFileMetadata instance = new QuickIOFileMetadata( @"C:\test.txt", data ); - instance.FullName.Should().Be( @"C:\test.txt" ); - instance.FullNameUnc.Should().Be( @"\\?\C:\test.txt" ); - instance.Name.Should().Be( @"test.txt" ); - - } - } -} diff --git a/test/SchwabenCode.QuickIO.UnitTests/QuickIOFileSystemEntryTests.cs b/test/SchwabenCode.QuickIO.UnitTests/QuickIOFileSystemEntryTests.cs deleted file mode 100644 index a57c2b7..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/QuickIOFileSystemEntryTests.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.IO; -using FluentAssertions; -using Xunit; - -namespace SchwabenCode.QuickIO.UnitTests -{ - public class QuickIOFileSystemEntryTests - { - [Fact] - public void QuickIOFileSystemEntryCtor() - { - QuickIOFileSystemEntry fse = new QuickIOFileSystemEntry(@"C:\temp\quickio", - QuickIOFileSystemEntryType.Directory, FileAttributes.Directory | FileAttributes.Hidden, 1024); - - fse.Should().NotBe(null); - - fse.Path.Should().Be(@"C:\temp\quickio"); - fse.GetPathUnc().Should().Be(@"\\?\C:\temp\quickio"); - fse.GetPathRegular().Should().Be(@"C:\temp\quickio"); - - fse.Type.Should().Be(QuickIOFileSystemEntryType.Directory); - - fse.Attributes.Contains(FileAttributes.Directory).Should().BeTrue(); - fse.Attributes.Contains(FileAttributes.Hidden).Should().BeTrue(); - fse.Attributes.Contains(FileAttributes.Encrypted).Should().BeFalse(); - - fse.Bytes.Should().Be(1024); - } - } -} diff --git a/test/SchwabenCode.QuickIO.UnitTests/QuickIOHashTests.cs b/test/SchwabenCode.QuickIO.UnitTests/QuickIOHashTests.cs deleted file mode 100644 index d5d0263..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/QuickIOHashTests.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.InteropServices.ComTypes; -using System.Security.Cryptography; -using System.Text; -using System.Threading.Tasks; -using FluentAssertions; -using Xunit; - -namespace SchwabenCode.QuickIO.UnitTests -{ - public class QuickIOHashTests - { - [Theory] - [InlineData( "Benjamin Abt SchwabenCode", "84c7ab34d2e4dbf1bc9d72f97f356f3defa34ebd" )] - public void CalculateHashSHA1( string testString, string expectedHash ) - { - - QuickIOHashResult result = QuickIOHash.Calculate( new SHA1Managed(), testString ); - result.Format().Should().Be( expectedHash ); - } - } -} diff --git a/test/SchwabenCode.QuickIO.UnitTests/QuickIOPathTests.cs b/test/SchwabenCode.QuickIO.UnitTests/QuickIOPathTests.cs deleted file mode 100644 index 7c97497..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/QuickIOPathTests.cs +++ /dev/null @@ -1,487 +0,0 @@ -using System; -using FluentAssertions; -using Xunit; - -namespace SchwabenCode.QuickIO.UnitTests -{ - public class QuickIOPathTests - { - [Fact] - public void GetRandomFileName() - { - string test = QuickIOPath.GetRandomFileName(); - test.Should().NotBeNullOrEmpty(); - test.Should().NotBeNullOrWhiteSpace(); - } - - [Theory] - [InlineData( "folder1", "folder1" )] - [InlineData( null, null )] - [InlineData( "folder1 ", "folder1" )] - [InlineData( "folder1\\", "folder1" )] - [InlineData( "\\folder1\\", "folder1" )] - [InlineData( " \\ folder1 \\ ", "folder1" )] - public void Clean( string p1, string expected ) - { - QuickIOPath.Clean( p1 ).Should().Be( expected ); - } - - [Theory] - [InlineData( "folder1", "folder2", @"folder1\folder2" )] - [InlineData( @"C:\folder1", "folder2", @"C:\folder1\folder2" )] - [InlineData( @"\\server\share\folder1", "folder2", @"\\server\share\folder1\folder2" )] - [InlineData( @"C:\temp", "test", @"C:\temp\test" )] - public void Combine( string p1, string p2, string expected ) - { - string result = QuickIOPath.Combine( p1, p2 ); - - result.Should().Be( System.IO.Path.Combine( p1, p2 ) ); - result.Should().Be( expected ); - } - - - [Fact] - public void Combine_ArgumentNullException() - { - Action actionNullParameter = () => QuickIOPath.Combine( "", null ); - Action actionNoParameter = () => QuickIOPath.Combine(); - - actionNullParameter.ShouldThrow(); - actionNoParameter.ShouldThrow(); - - } - - [Theory] - [InlineData( null, null )] - [InlineData( "", "" )] - [InlineData( @"dsadasdasdasdasd", "" )] - [InlineData( @"folder\file", "" )] - [InlineData( @"C:\", @"C:\" )] - [InlineData( @"C:\folder", @"C:\" )] - [InlineData( @"C:\file.txt", @"C:\" )] - [InlineData( @"C:\folder\file.txt", @"C:\" )] - [InlineData( @"\\server\share", @"\\server\share" )] - [InlineData( @"\\server\share\", @"\\server\share" )] - [InlineData( @"\\server\share\folder", @"\\server\share" )] - [InlineData( @"\\server\share\file.txt", @"\\server\share" )] - [InlineData( @"\\server\share\folder\file.txt", @"\\server\share" )] - [InlineData( @"\\?\C:\", @"\\?\C:\" )] - [InlineData( @"\\?\C:\folder", @"\\?\C:\" )] - [InlineData( @"\\?\C:\file.txt", @"\\?\C:\" )] - [InlineData( @"\\?\C:\folder\file.txt", @"\\?\C:\" )] - [InlineData( @"\\?\UNC\server\share", @"\\?\UNC\server\share" )] - [InlineData( @"\\?\UNC\server\share\", @"\\?\UNC\server\share" )] - [InlineData( @"\\?\UNC\server\share\folder", @"\\?\UNC\server\share" )] - [InlineData( @"\\?\UNC\server\share\file.txt", @"\\?\UNC\server\share" )] - [InlineData( @"\\?\UNC\server\share\folder\file.txt", @"\\?\UNC\server\share" )] - public void GetPathRoot( string test, string expected ) - { - QuickIOPath.GetPathRoot( test ).Should().Be( expected ); - } - - - [Theory] - [InlineData( "", null, true )] - [InlineData( " ", null, true )] - [InlineData( null, null, false )] - [InlineData( @"C:\", null, false )] - [InlineData( @" C:\ ", null, false )] - [InlineData( @"\server", null, true )] - [InlineData( @" \\server\share ", null, false )] - - [InlineData( @"C:\folder\text.txt", @"C:\folder", false )] - [InlineData( @"folder\text.txt", "folder", true )] - public void GetDirectoryName( string test, string expected, bool differsFromSystemIO ) - { - string result = QuickIOPath.GetDirectoryName( test ); - result.Should().Be( expected ); - - if( !differsFromSystemIO ) - { - result.Should().Be( System.IO.Path.GetDirectoryName( test ), "Syste.IO differs" ); - } - } - - [Theory] - [InlineData( @"folder\text.txt", "text.txt" )] - [InlineData( @"C:\folder\text.txt", "text.txt" )] - [InlineData( @"text.txt", "text.txt" )] - [InlineData( @"", "" )] - [InlineData( @"C:\folder\folder2\", "folder2" )] - public void GetName( string test, string expected ) - { - QuickIOPath.GetName( test ).Should().Be( expected ); - } - - [Fact] - public void GetFullPath() - { - string[ ] pathList = new string[ ] - { - @"_TestFiles\TextFile.txt", - @"C:\temp" - }; - foreach( var entry in pathList ) - { - QuickIOPath.GetFullPath( entry ).Should().Be( System.IO.Path.GetFullPath( entry ) ); - } - } - - [Fact] - public void GetFullPathUnc() - { - string path = @"\\?\UNC\Server\Share\File.txt"; - QuickIOPath.GetFullPath( path ).Should().Be( path ); - } - - [Theory] - [InlineData( @"C:", false )] - [InlineData( @"1:", false )] - [InlineData( @"\\*\*", false )] - [InlineData( @"\\?\UNC\*\*\", false )] - [InlineData( @"\\server\name", false )] - [InlineData( @"\\?\UNC\\server\name", false )] - [InlineData( @"\\?\C:\", false )] - [InlineData( @"C:\", true )] - [InlineData( @"c:\", true )] - [InlineData( @"C:\sadasd", true )] - [InlineData( @"c:\sadasd", true )] - public void IsLocalRegular( string test, bool expected ) - { - QuickIOPath.IsLocalRegular( test ).Should().Be( expected ); - } - - - [Theory] - [InlineData( @"C:", false )] - [InlineData( @"1:", false )] - [InlineData( @"\\?\C:\", false )] - [InlineData( @"C:\", false )] - [InlineData( @"c:\", false )] - [InlineData( @"C:\sadasd", false )] - [InlineData( @"c:\sadasd", false )] - [InlineData( @"\\", false )] - [InlineData( @"\\server", false )] - [InlineData( @"c:\sadasd", false )] - [InlineData( @"\\server\", false )] - [InlineData( @"\\?\UNC\server\name", false )] - [InlineData( @"\\*\*", false )] - [InlineData( @"\\?\UNC\*\*\", false )] - [InlineData( @"\\server\name", true )] - [InlineData( @"\\server\name\", true )] - [InlineData( @"\\server\name\folder", true )] - public void IsShareRegular( string test, bool expected ) - { - QuickIOPath.IsShareRegular( test ).Should().Be( expected ); - } - - - [Theory] - [InlineData( @"\\server\name", false )] - [InlineData( @"\\*\*", false )] - [InlineData( @"\\?\UNC\*\*\", false )] - [InlineData( @"\\?\C:", false )] - [InlineData( @"\\?\C:\", false )] - [InlineData( @"\\?\c:\", false )] - [InlineData( @"\\?\C:\sadasd", false )] - [InlineData( @"\\?\c:\sadasd", false )] - [InlineData( @"\\?\UNC\", false )] - [InlineData( @"\\?\UNC\server", false )] - [InlineData( @"\\?\UNC\server\", false )] - [InlineData( @"\\?\UNC\server\share", true )] - [InlineData( @"\\?\UNC\server\share\", true )] - public void IsShareUnc( string test, bool expected ) - { - QuickIOPath.IsShareUnc( test ).Should().Be( expected ); - } - - [Theory] - [InlineData( @"", false )] - [InlineData( @"\\server\", false )] - [InlineData( @"C", false )] - [InlineData( @"C:\", false )] - [InlineData( @"\\*\*", false )] - [InlineData( @"\\?\UNC\*\*\", false )] - [InlineData( @"\\server\share", false )] - [InlineData( @"\\server\share\", false )] - [InlineData( @"\\?\C:\", true )] - [InlineData( @"\\?\UNC\server\share", true )] - [InlineData( @"\\?\UNC\server\share\", true )] - public void IsUnc( string test, bool expected ) - { - QuickIOPath.IsUnc( test ).Should().Be( expected ); - } - - [Theory] - [InlineData( @"", false )] - [InlineData( @"\\*\*", false )] - [InlineData( @"\\?\UNC\*\*\", false )] - [InlineData( @"\\server\", false )] - [InlineData( @"C", false )] - [InlineData( @"C:\", false )] - [InlineData( @"\\server\share", false )] - [InlineData( @"\\server\share\", false )] - [InlineData( @"\\?\UNC\server\share", false )] - [InlineData( @"\\?\UNC\server\share\", false )] - [InlineData( @"\\?\C:\", true )] - public void IsLocalUnc( string test, bool expected ) - { - QuickIOPath.IsLocalUnc( test ).Should().Be( expected ); - } - - [Theory] - [InlineData( @"C:\", false )] - [InlineData( @"\\server\share", false )] - [InlineData( @"\\server\share\", false )] - [InlineData( @"\\?\UNC\server\share", false )] - [InlineData( @"\\?\UNC\server\share\", false )] - [InlineData( @"\\?\C:\", false )] - [InlineData( @"folder\file.txt", true )] - [InlineData( @"\\server\", true )] - public void IsRelative( string test, bool expected ) - { - QuickIOPath.IsRelative( test ).Should().Be( expected, because: test ); - } - - [Theory] - [InlineData( TestHelpers.AlphabethUpperCase, true )] - [InlineData( TestHelpers.AlphabethLowerCase, true )] - public void IsRootLocalRegular_TrueTestsLoop( string test, bool expected ) - { - // True - foreach( var c in test ) - { - QuickIOPath.IsRootLocalRegular( c + @":\" ).Should().Be( expected ); - } - } - - [Theory] - [InlineData( null, false )] - [InlineData( "", false )] - [InlineData( @" ", false )] - [InlineData( @"2:\", false )] - [InlineData( @"_:\", false )] - [InlineData( @"\\server", false )] - [InlineData( @"#:\", false )] - [InlineData( @"C:\folder", false )] - public void IsRootLocalRegular_FalseTests( string test, bool expected ) - { - QuickIOPath.IsRootLocalRegular( test ).Should().Be( expected ); - } - - [Theory] - [InlineData( null, false )] - [InlineData( "", false )] - [InlineData( @"C:", false )] - [InlineData( @"C:\", false )] - [InlineData( @"C:\folder", false )] - [InlineData( @"1:", false )] - [InlineData( @"\\*\*", false )] - [InlineData( @"\\?\UNC\*\*\", false )] - [InlineData( @"\\server\share", false )] - [InlineData( @"\\server\share\", false )] - [InlineData( @"\\server\share\folder", false )] - [InlineData( @"\\?\UNC\server\share", false )] - [InlineData( @"\\?\UNC\server\share\folder", false )] - [InlineData( @"\\?\C:", false )] - [InlineData( @"\\?\C:\folder", false )] - [InlineData( @"\\?\C:\", true )] - [InlineData( @"\\?\c:\", true )] - public void IsRootLocalUnc( string test, bool expected ) - { - QuickIOPath.IsRootLocalUnc( test ).Should().Be( expected ); - } - - [Theory] - [InlineData( null, false )] - [InlineData( "", false )] - [InlineData( @"\\*\*", false )] - [InlineData( @"\\?\UNC\*\*\", false )] - [InlineData( @"\\?\C:", false )] - [InlineData( @"\\?\C:\", false )] - [InlineData( @"\\?\c:\", false )] - [InlineData( @"\\?\C:\sadasd", false )] - [InlineData( @"\\?\c:\sadasd", false )] - [InlineData( @"\\server\share\folder", false )] - [InlineData( @"\\server\share", true )] - [InlineData( @"\\server\share\", true )] - [InlineData( @"\\?\UNC\server\share", false )] - public void IsRootShareRegular( string test, bool expected ) - { - QuickIOPath.IsRootShareRegular( test ).Should().Be( expected ); - } - - - [Theory] - [InlineData( null, false )] - [InlineData( "", false )] - [InlineData( @"\\*\*", false )] - [InlineData( @"\\?\UNC\*\*\", false )] - [InlineData( @"\\?\C:", false )] - [InlineData( @"\\?\C:\", false )] - [InlineData( @"\\?\c:\", false )] - [InlineData( @"\\?\C:\sadasd", false )] - [InlineData( @"\\?\c:\sadasd", false )] - [InlineData( @"\\server\share", false )] - [InlineData( @"\\server\share\", false )] - [InlineData( @"\\server\share\folder", false )] - [InlineData( @"\\?\UNC\", false )] - [InlineData( @"\\?\UNC\server\", false )] - [InlineData( @"\\?\UNC\server\share", true )] - [InlineData( @"\\?\UNC\server\share\", true )] - [InlineData( @"\\?\UNC\server\share\folder", false )] - [InlineData( @"\\?\UNC\server\share\folder\", false )] - public void IsRootShareUnc( string test, bool expected ) - { - QuickIOPath.IsRootShareUnc( test ).Should().Be( expected ); - } - - [Theory] - [InlineData( " ", false )] - [InlineData( " ", false )] - [InlineData( ".", false )] - [InlineData( "..", false )] - [InlineData( "/", false )] - [InlineData( "\\", false )] - [InlineData( "<", false )] - [InlineData( ">", false )] - [InlineData( "*", false )] - [InlineData( "?", false )] - [InlineData( ":", false )] - [InlineData( "\0", false )] - [InlineData( ".point", false )] - [InlineData( "point.", false )] - [InlineData( " invalid", false )] - [InlineData( "invalid ", false )] - - [InlineData( "_", true )] - [InlineData( "♥", true )] - [InlineData( "%", true )] - [InlineData( "folder", true )] - [InlineData( "folder.name", true )] - [InlineData( "folder_name", true )] - public void IsValidFolderName( string test, bool expected ) - { - QuickIOPath.IsValidFolderName( test ).Should().Be( expected ); - } - - [Fact] - public void IsValidFolderName_MaxLength_Exceeded() - { - QuickIOPath.IsValidFolderName( new string( 'a', QuickIOPath.MaxFolderNameLength + 1 ) ).Should().Be( false ); - } - - [Theory] - [InlineData( '<', false )] - [InlineData( '>', false )] - [InlineData( ':', false )] - [InlineData( '"', false )] - [InlineData( '/', false )] - [InlineData( '\\', false )] - [InlineData( '|', false )] - [InlineData( '?', false )] - [InlineData( '*', false )] - [InlineData( '\0', false )] - [InlineData( '_', true )] - [InlineData( '♥', true )] - [InlineData( 'A', true )] - [InlineData( '-', true )] - [InlineData( 'c', true )] - [InlineData( '3', true )] - [InlineData( '.', true )] - [InlineData( ' ', true )] - public void IsValidFolderChar( char test, bool expected ) - { - QuickIOPath.IsValidFolderChar( test ).Should().Be( expected ); - } - - - [Theory] - [InlineData( '_', false )] - [InlineData( '1', false )] - [InlineData( '%', false )] - [InlineData( ' ', false )] - [InlineData( '#', false )] - [InlineData( '♥', false )] - [InlineData( 'A', true )] - [InlineData( 'R', true )] - [InlineData( 'Z', true )] - [InlineData( 'a', true )] - [InlineData( 'r', true )] - [InlineData( 'z', true )] - public void IsValidDriveLetter( char test, bool expected ) - { - QuickIOPath.IsValidDriveLetter( test ).Should().Be( expected ); - } - - [Theory] - [InlineData( " ", false )] - [InlineData( "@", false )] - [InlineData( ", ", false )] - [InlineData( " invalid", false )] - [InlineData( "invalid ", false )] - [InlineData( "valid", true )] - [InlineData( "valid2", true )] - public void IsValidServerName( string test, bool expected ) - { - QuickIOPath.IsValidServerName( test ).Should().Be( expected ); - - } - - [Theory] - [InlineData( " ", false )] - [InlineData( "@", false )] - [InlineData( ", ", false )] - [InlineData( "valid", true )] - [InlineData( "valid2", true )] - public void IsValidShareName( string test, bool expected ) - { - QuickIOPath.IsValidShareName( test ).Should().Be( expected ); - } - - [Theory] - [InlineData( @"\\serverName\shareName", "serverName", "shareName", true )] - public void TryGetServerAndShareNameFromLocation( string test, string serverNameExpected, string shareNameExpected, bool parseResultExpected ) - { - string serverName, shareName; - - QuickIOPath.TryParseShare( test, QuickIOPathType.Regular, out serverName, out shareName ).Should().Be( parseResultExpected ); - serverName.Should().Be( serverNameExpected ); - shareName.Should().Be( shareNameExpected ); - } - - [Theory] - [InlineData( @"\\?\UNC\serverName\shareName\folder\file.txt", @"\\?\UNC\serverName\shareName", true )] - [InlineData( @"\\serverName\shareName\folder\file.txt", null, false )] - public void TryGetShareUncRootPath( string test, string rootExpected, bool parseResultExpected ) - { - string root; - - QuickIOPath.TryGetShareUncRootPath( test, out root ).Should().Be( parseResultExpected ); - root.Should().Be( rootExpected ); - } - - - [Theory] - [InlineData( @"C:\test\path", @"C:\test\path" )] - [InlineData( @"\\?\C:\test\path", @"C:\test\path" )] - [InlineData( @"\\test\path", @"\\test\path" )] - [InlineData( @"\\?\UNC\test\path", @"\\test\path" )] - [InlineData( @"relative\path", @"relative\path" )] - public void ToPathRegular( string test, string expected ) - { - QuickIOPath.ToPathRegular( test ).Should().Be( expected ); - } - - [Theory] - [InlineData( @"C:\test\path", @"\\?\C:\test\path" )] - [InlineData( @"\\?\C:\test\path", @"\\?\C:\test\path" )] - [InlineData( @"\\test\path", @"\\?\UNC\test\path" )] - [InlineData( @"\\?\UNC\test\path", @"\\?\UNC\test\path" )] - [InlineData( @"relative\path", @"relative\path" )] - public void ToPathUnc( string test, string expected ) - { - QuickIOPath.ToPathUnc( test ).Should().Be( expected ); - } - } -} diff --git a/test/SchwabenCode.QuickIO.UnitTests/QuickIOPatternsTests.cs b/test/SchwabenCode.QuickIO.UnitTests/QuickIOPatternsTests.cs deleted file mode 100644 index e3f54f1..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/QuickIOPatternsTests.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using FluentAssertions; -using Xunit; - -namespace SchwabenCode.QuickIO.UnitTests -{ - public class QuickIOPatternsTests - { - [Fact] - public void PathMatchAllTest( ) - { - QuickIOPatterns.PathMatchAll.Should().Be( "*" ); - } - } -} diff --git a/test/SchwabenCode.QuickIO.UnitTests/SchwabenCode.QuickIO.UnitTests.csproj b/test/SchwabenCode.QuickIO.UnitTests/SchwabenCode.QuickIO.UnitTests.csproj deleted file mode 100644 index 5848340..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/SchwabenCode.QuickIO.UnitTests.csproj +++ /dev/null @@ -1,112 +0,0 @@ - - - - - - Debug - AnyCPU - {4867DD64-C401-4139-84F7-4252E138CC9B} - Library - Properties - SchwabenCode.QuickIO.UnitTests - SchwabenCode.QuickIO.UnitTests - v4.6 - 512 - - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\packages\FluentAssertions.4.14.0\lib\net45\FluentAssertions.dll - True - - - ..\..\packages\FluentAssertions.4.14.0\lib\net45\FluentAssertions.Core.dll - True - - - - - - - - - - - ..\..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll - True - - - ..\..\packages\xunit.assert.2.1.0\lib\dotnet\xunit.assert.dll - True - - - ..\..\packages\xunit.extensibility.core.2.1.0\lib\dotnet\xunit.core.dll - True - - - ..\..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll - True - - - - - - - - - - - - - - - - - - - - - {b33dbcee-42f4-4570-b4ef-5412ce4a4bda} - SchwabenCode.QuickIO - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - \ No newline at end of file diff --git a/test/SchwabenCode.QuickIO.UnitTests/TestClasses/TestExceptionClass.cs b/test/SchwabenCode.QuickIO.UnitTests/TestClasses/TestExceptionClass.cs deleted file mode 100644 index 949fee9..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/TestClasses/TestExceptionClass.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace SchwabenCode.QuickIO.UnitTests.TestClasses -{ - public class TestExceptionClass : QuickIOBaseException - { - public TestExceptionClass( string message, string path ) : base( message, path ) - { - } - - public TestExceptionClass( string message, string path, Exception innerException ) : base( message, path, innerException ) - { - } - } -} diff --git a/test/SchwabenCode.QuickIO.UnitTests/TestHelpers.cs b/test/SchwabenCode.QuickIO.UnitTests/TestHelpers.cs deleted file mode 100644 index ddd0f9a..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/TestHelpers.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace SchwabenCode.QuickIO.UnitTests -{ - public static class TestHelpers - { - public const String AlphabethUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - public const String AlphabethLowerCase = "abcdefghijklmnopqrstuzwxyz"; - } -} diff --git a/test/SchwabenCode.QuickIO.UnitTests/UnitTestBase.cs b/test/SchwabenCode.QuickIO.UnitTests/UnitTestBase.cs deleted file mode 100644 index 93eb11c..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/UnitTestBase.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.IO; -using System.Reflection; - -namespace SchwabenCode.QuickIO.UnitTests -{ - public abstract class UnitTestBase - { - - } -} diff --git a/test/SchwabenCode.QuickIO.UnitTests/Win32FindDataTestValue.cs b/test/SchwabenCode.QuickIO.UnitTests/Win32FindDataTestValue.cs deleted file mode 100644 index 073c114..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/Win32FindDataTestValue.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.IO; -using SchwabenCode.QuickIO.Win32; - -namespace SchwabenCode.QuickIO.UnitTests -{ - public class Win32FindDataTestValue : Win32FindData - { - public Win32FindDataTestValue() - { - this.dwFileAttributes = FileAttributes.Compressed | FileAttributes.Normal | - FileAttributes.ReadOnly; - this.ftCreationTime_dwLowDateTime = 1; - this.ftCreationTime_dwHighDateTime = 2; - this.ftLastAccessTime_dwLowDateTime = 3; - this.ftLastAccessTime_dwHighDateTime = 4; - this.ftLastWriteTime_dwLowDateTime = 5; - this.ftLastWriteTime_dwHighDateTime = 6; - this.nFileSizeHigh = 7; - this.nFileSizeLow = 8; - this.dwReserved0 = 9; - this.dwReserved1 = 0; - - - this.cFileName = "test.txt"; - this.cAlternateFileName = "test.txt"; - } - - } -} \ No newline at end of file diff --git a/test/SchwabenCode.QuickIO.UnitTests/packages.config b/test/SchwabenCode.QuickIO.UnitTests/packages.config deleted file mode 100644 index 5915f5b..0000000 --- a/test/SchwabenCode.QuickIO.UnitTests/packages.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/tests/QuickIO.IntegrationTests/QuickIO.IntegrationTests.csproj b/tests/QuickIO.IntegrationTests/QuickIO.IntegrationTests.csproj new file mode 100644 index 0000000..26528d5 --- /dev/null +++ b/tests/QuickIO.IntegrationTests/QuickIO.IntegrationTests.csproj @@ -0,0 +1,25 @@ + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/tests/QuickIO.IntegrationTests/QuickIO_Directory_Enumeration_Tests.cs b/tests/QuickIO.IntegrationTests/QuickIO_Directory_Enumeration_Tests.cs new file mode 100644 index 0000000..fe803c7 --- /dev/null +++ b/tests/QuickIO.IntegrationTests/QuickIO_Directory_Enumeration_Tests.cs @@ -0,0 +1,19 @@ +//using Xunit; + +//namespace SchwabenCode.QuickIO.UnitTests; + +//public class QuickIO_Directory_Enumerations_Tests +//{ +// [Fact] +// public void Directory_EnumerateFilePaths_Share_Test() +// { +// string path = @"\\testnas\quickiodirectory"; + +// QuickIODirectoryInfo dirInfo = new( path ); +// List allDircs1 = dirInfo.EnumerateFilePaths( QuickIOPatternConstants.All, SearchOption.TopDirectoryOnly ).ToList( ); +// List allDircs2 = QuickIODirectory.EnumerateFilePaths( path, QuickIOPatternConstants.All, SearchOption.TopDirectoryOnly, QuickIOPathType.Regular ).ToList( ); + +// Assert.True(allDircs1.Count != 0); +// Assert.True(allDircs2.Count != 0); +// } +//} diff --git a/tests/QuickIO.IntegrationTests/QuickIO_Directory_Exists.cs b/tests/QuickIO.IntegrationTests/QuickIO_Directory_Exists.cs new file mode 100644 index 0000000..0ff7a8d --- /dev/null +++ b/tests/QuickIO.IntegrationTests/QuickIO_Directory_Exists.cs @@ -0,0 +1,24 @@ +//using Xunit; + +//namespace SchwabenCode.QuickIO.IntegrationTests; + +//public class QuickIO_Directory_Exists +//{ +// [Fact] +// public void Directory_Exists_LocalRoot_OK() +// { +// string drive = @"C:\"; +// QuickIOPathInfo qio = new( drive ); +// Assert.True(qio.Exists, "Main not found: " + drive); + +// Assert.True(QuickIODirectory.Exists(drive), drive + " not found."); +// } + + +// [Fact] +// public void Directory_Ctor_Share() +// { +// string share = @"\\testnas\quickiodirectory"; +// _ = new QuickIODirectoryInfo(share); +// } +//} diff --git a/tests/QuickIO.IntegrationTests/TransferTestConsole.cs b/tests/QuickIO.IntegrationTests/TransferTestConsole.cs new file mode 100644 index 0000000..bdaee41 --- /dev/null +++ b/tests/QuickIO.IntegrationTests/TransferTestConsole.cs @@ -0,0 +1,41 @@ +//using SchwabenCode.QuickIO.Transfer; + +//namespace SchwabenCode.QuickIO.IntegrationTests; + +//internal class TransferTestConsole +//{ +// private static void Main(string[] args) +// { +// const string sourceFile = @"C:\transfer_test\source\test.txt"; +// const string targetDirectory = @"C:\transfer_test\to"; + +// IQuickIOTransferObserver observer = new QuickIOTransferObserver( ); +// QuickIOTransferFileCopyService service = new( observer, new QuickIOFileInfo( sourceFile ), targetDirectory, threadCount: 1, retryCount: 3, overwrite: true ); + +// // Progress information +// observer.FileCopyStarted += OnFileCopyStarted; +// observer.FileCopyProgress += OnFileProgressUpdate; +// observer.FileCopyFinished += OnFileCopyFinished; + +// // Start progress +// service.Start(); // Blocks thread until finished + +// Console.WriteLine("Finished"); +// _ = Console.ReadKey(); +// } + +// private static void OnFileCopyFinished(object sender, QuickIOTransferFileCopyFinishedEventArgs e) +// { +// Console.WriteLine("Finished: " + e.SourcePath + " - MB/s: " + (e.BytesPerSecond / 1024.0 / 1024.0).ToString("0.0")); +// } + +// private static void OnFileCopyStarted(object sender, QuickIOTransferFileCopyStartedEventArgs e) +// { +// Console.WriteLine("Started: " + e.SourcePath + " to " + e.TargetPath + " (Bytes: " + e.TotalBytes + ")"); +// } + +// private static void OnFileProgressUpdate(object sender, QuickIOTransferFileCopyProgressEventArgs e) +// { +// Console.WriteLine("Progress: " + e.SourcePath + " - %: " + e.Percentage + " MB/s: " + (e.BytesPerSecond / 1024.0 / 1024.0).ToString("0.0")); +// } +//} diff --git a/tests/QuickIO.UnitTests/QuickIO.UnitTests.csproj b/tests/QuickIO.UnitTests/QuickIO.UnitTests.csproj new file mode 100644 index 0000000..cef79a5 --- /dev/null +++ b/tests/QuickIO.UnitTests/QuickIO.UnitTests.csproj @@ -0,0 +1,47 @@ + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + Always + + + Always + + + Always + + + Always + + + Always + + + Always + + + + diff --git a/tests/QuickIO.UnitTests/QuickIO_DirectoryInfo_Tests.cs b/tests/QuickIO.UnitTests/QuickIO_DirectoryInfo_Tests.cs new file mode 100644 index 0000000..2df4e6f --- /dev/null +++ b/tests/QuickIO.UnitTests/QuickIO_DirectoryInfo_Tests.cs @@ -0,0 +1,38 @@ +using Xunit; + +namespace SchwabenCode.QuickIO.UnitTests; + + +public class QuickIO_DirectoryInfo_Tests +{ + [Fact] + public void QuickIODirectoryInfo_Explizit_Cast() + { + string tempDir = Guid.NewGuid( ).ToString( ); + _ = Directory.CreateDirectory(tempDir); + + DirectoryInfo di = new( tempDir ); + Assert.True(di.Exists); + + QuickIODirectoryInfo QuickIODirectoryInfo = ( QuickIODirectoryInfo ) di; + Assert.NotNull(QuickIODirectoryInfo); + } + + [Fact] + public void QuickIOFileInfo_AsFileInfo_Test() + { + string tempDir = Guid.NewGuid( ).ToString( ); + _ = Directory.CreateDirectory(tempDir); + + DirectoryInfo di = new( tempDir ); + Assert.True(di.Exists); + + QuickIODirectoryInfo QuickIODirectoryInfo = ( QuickIODirectoryInfo ) di; + Assert.NotNull(QuickIODirectoryInfo); + + DirectoryInfo di2 = QuickIODirectoryInfo.AsDirectoryInfo( ); + Assert.NotNull(di2); + + Assert.Equal(tempDir, di2.Name); + } +} diff --git a/tests/QuickIO.UnitTests/QuickIO_Directory_Enumeration_Tests.cs b/tests/QuickIO.UnitTests/QuickIO_Directory_Enumeration_Tests.cs new file mode 100644 index 0000000..b01762d --- /dev/null +++ b/tests/QuickIO.UnitTests/QuickIO_Directory_Enumeration_Tests.cs @@ -0,0 +1,102 @@ +using System.Diagnostics; +using FluentAssertions; +using Xunit; + +namespace SchwabenCode.QuickIO.UnitTests; + +public class QuickIO_Directory_Enumerations_Tests +{ + [Fact] + public void Directory_EnumerateDirectoryPaths_Test() + { + string testFolder = Path.GetFullPath( "TestFiles/" ); + string testPath1 = Path.Combine( testFolder, "RandomTestFolder__Directory_ENUM_1_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + string testPath2 = Path.Combine( testFolder, "RandomTestFolder__Directory_ENUM_2_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + + QuickIODirectory.Create(testPath1); + QuickIODirectory.Create(testPath2); + + List allDircs = QuickIODirectory.EnumerateDirectoryPaths( testFolder, QuickIOPatternConstants.All, SearchOption.TopDirectoryOnly, QuickIOPathType.Regular ).ToList( ); + + Assert.True(allDircs.Count(x => x.Equals(testPath1)) == 1, "Directory not found."); + Assert.True(allDircs.Count(x => x.Equals(testPath2)) == 1, "Directory not found."); + + QuickIODirectory.Delete(testPath1); + QuickIODirectory.Delete(testPath2); + } + + [Fact] + public void Directory_EnumerateFilePaths_Test() + { + string testFolder = Path.GetFullPath( "TestFiles/" ); + string testPath1 = Path.Combine( testFolder, "RandomTestFolder__Directory_ENUM_1_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + string testPath2 = Path.Combine( testFolder, "RandomTestFolder__Directory_ENUM_2_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + + QuickIOFile.Create(testPath1); + QuickIOFile.Create(testPath2); + + List allDircs = QuickIODirectory.EnumerateFilePaths( testFolder, QuickIOPatternConstants.All, SearchOption.TopDirectoryOnly, QuickIOPathType.Regular ).ToList( ); + + Assert.True(allDircs.Count(x => x.Equals(testPath1)) == 1, "File1 not found."); + Assert.True(allDircs.Count(x => x.Equals(testPath2)) == 1, "File2 not found."); + + QuickIOFile.Delete(testPath1); + QuickIOFile.Delete(testPath2); + } + + [Fact] + public void Directory_EnumerateMetadata_Test() + { + string testFolder = Path.GetFullPath( "TestFiles" ); + + QuickIODirectoryMetadata? metadata = QuickIODirectory.GetMetadata( testFolder ); + Assert.NotNull(metadata); + + foreach (QuickIOFileMetadata file in metadata.Files) + { + Debug.WriteLine("File: " + file.Name); + } + foreach (QuickIODirectoryMetadata dir in metadata.Directories) + { + Debug.WriteLine("Directory: " + dir.Name); + } + + bool fileItem = metadata.Files.Any( x => x.Name == "Test.txt" ); + bool directoryItem = metadata.Directories.Any( x => x.Name == "DirTimeTest" ); + + Assert.True(fileItem, "File not found."); + Assert.True(directoryItem, "Directory not found."); + } + + [Fact] + public void Directory_Readonly_Test() + { + string testfile = Path.Combine( Path.GetFullPath( "TestFiles/" ), Path.GetRandomFileName( ) ); + + QuickIODirectory.Create(testfile); + QuickIODirectory.SetAttributes(testfile, FileAttributes.ReadOnly); + + Assert.True(QuickIODirectory.GetAttributes(testfile).HasFlag(FileAttributes.ReadOnly), "Hidden not set"); + } + + [Fact] + public void Directory_HiddenDir_Test() + { + string testfile = Path.Combine( Path.GetFullPath( "TestFiles/" ), Path.GetRandomFileName( ) ); + + QuickIODirectory.Create(testfile); + QuickIODirectory.SetAttributes(testfile, FileAttributes.Hidden); + + + Assert.True(QuickIODirectory.GetAttributes(testfile).HasFlag(FileAttributes.Hidden), "Hidden not set"); + } + + [Fact] + public void Directory_AttrFail_Test() + { + string testfile = Path.Combine( Path.GetFullPath( "TestFiles/" ), "AttrFail_" + Path.GetRandomFileName( ) ); + + Action act = () => QuickIODirectory.GetAttributes(testfile).HasFlag(FileAttributes.Hidden); + act.Should().Throw(); + } +} diff --git a/tests/QuickIO.UnitTests/QuickIO_Directory_Tests.cs b/tests/QuickIO.UnitTests/QuickIO_Directory_Tests.cs new file mode 100644 index 0000000..875c184 --- /dev/null +++ b/tests/QuickIO.UnitTests/QuickIO_Directory_Tests.cs @@ -0,0 +1,97 @@ +using FluentAssertions; +using Xunit; + +namespace SchwabenCode.QuickIO.UnitTests; + +public class QuickIO_Directory_Tests +{ + [Fact] + public void Directory_Create_Test() + { + string testFolder = Path.GetFullPath( "TestFiles/" ); + string testPath = Path.Combine( testFolder, "RandomTestFolder_Directory_CREATE_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + + QuickIODirectory.Create(testPath); + + List allDirs = QuickIODirectory.EnumerateDirectoryPaths( testFolder, QuickIOPatternConstants.All, SearchOption.TopDirectoryOnly, QuickIOPathType.Regular ).ToList( ); + Assert.True(allDirs.Count(x => x.Equals(testPath)) == 1, "Directory not created."); + } + + + [Fact] + public void Directory_Delete_Test() + { + string testFolder = Path.GetFullPath( "TestFiles/" ); + string testPath = Path.Combine( testFolder, "RandomTestFolder_Directory_DELETE_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + + QuickIODirectory.Create(testPath); + + List allDircs = QuickIODirectory.EnumerateDirectoryPaths( testFolder, QuickIOPatternConstants.All, SearchOption.TopDirectoryOnly, QuickIOPathType.Regular ).ToList( ); + Assert.True(allDircs.Count(x => x.Equals(testPath)) == 1, "Directory not created."); + + QuickIODirectory.Delete(testPath); + + + allDircs = QuickIODirectory.EnumerateDirectoryPaths(testFolder, QuickIOPatternConstants.All, SearchOption.TopDirectoryOnly, QuickIOPathType.Regular).ToList(); + Assert.True(allDircs.Count(x => x.Equals(testPath, StringComparison.Ordinal)) == 0, "Directory not removed."); + } + + [Fact] + public void Directory_Delete_Tree_Test() + { + string testFolder = Path.GetFullPath( "TestFiles/DELETE/" ); + string testPath1 = Path.Combine( testFolder, "RandomTestFolder_Directory_DELETE_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + string testPath2 = Path.Combine( testPath1, "RandomTestFolder_Directory_DELETE_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + string testPath3 = Path.Combine( testPath2, "RandomTestFolder_Directory_DELETE_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + string testPath4 = Path.Combine( testPath3, "RandomTestFolder_Directory_DELETE_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + string testPath5 = Path.Combine( testPath4, "RandomTestFolder_Directory_DELETE_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + string testPath6 = Path.Combine( testPath5, "RandomTestFolder_Directory_DELETE_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + string testPath7 = Path.Combine( testPath6, "RandomTestFolder_Directory_DELETE_Test_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) ); + + QuickIODirectory.Create(testPath7, true); + + QuickIODirectory.Delete(testFolder, true); + } + + + [Fact] + public void Directory_Exists_Test() + { + string currentDirc = Environment.CurrentDirectory; + + Assert.True(Directory.Exists(currentDirc), "Failed 1"); + Assert.True(QuickIODirectory.Exists(currentDirc), "Failed 2"); + + Assert.False(Directory.Exists(currentDirc + "a"), "Failed 3"); + Assert.False(QuickIODirectory.Exists(Path.GetFullPath(currentDirc + "a")), "Failed 4"); + } + + [Fact] + public void Directory_SetWriteTime_Test() + { + string currentDirc = Path.GetFullPath( "TestFiles/DirTimeTest" ); + QuickIODirectoryInfo dirInfo = new( currentDirc ); + + DateTime newTime = DateTime.Now.AddDays( -1 ); + + QuickIODirectory.SetAllFileTimesUtc(dirInfo, newTime, newTime, newTime); + + QuickIODirectory.GetLastWriteTime(dirInfo).Should().Be(newTime); + QuickIODirectory.GetLastAccessTime(dirInfo).Should().Be(newTime); + QuickIODirectory.GetCreationTime(dirInfo).Should().Be(newTime); + } + + // TODO + //[Fact] + //public void Directory_Enumeration_NoAccess() + //{ + // Action act = () => QuickIODirectory.EnumerateDirectoryPaths(@"C:\temp\quickiotest"); + // act.Should().Throw(); + //} + + [Fact] + public void Directory_Enumeration_NoAccessIgnored() + { + QuickIODirectory.EnumerateDirectoryPaths(@"C:\temp", enumerateOptions: QuickIOEnumerateOptions.SuppressAllExceptions); + } +} diff --git a/tests/QuickIO.UnitTests/QuickIO_FileInfo_Tests.cs b/tests/QuickIO.UnitTests/QuickIO_FileInfo_Tests.cs new file mode 100644 index 0000000..ce26499 --- /dev/null +++ b/tests/QuickIO.UnitTests/QuickIO_FileInfo_Tests.cs @@ -0,0 +1,37 @@ +using Xunit; + +namespace SchwabenCode.QuickIO.UnitTests; + +public class QuickIO_FileInfo_Tests +{ + [Fact] + public void QuickIOFileInfo_Explizit_Cast() + { + string tempFile = Guid.NewGuid( ).ToString( ); + File.Create(tempFile); + + FileInfo fi = new( tempFile ); + Assert.True(fi.Exists); + + QuickIOFileInfo QuickIOFileInfo = ( QuickIOFileInfo ) fi; + Assert.NotNull(QuickIOFileInfo); + } + + [Fact] + public void QuickIOFileInfo_AsFileInfo_Test() + { + string tempFile = Path.GetTempPath( ) + Guid.NewGuid( ); + File.Create(tempFile); + + FileInfo fi = new( tempFile ); + Assert.True(fi.Exists); + + QuickIOFileInfo QuickIOFileInfo = ( QuickIOFileInfo ) fi; + Assert.NotNull(QuickIOFileInfo); + + FileInfo fi2 = QuickIOFileInfo.AsFileInfo( ); + Assert.NotNull(fi2); + + Assert.Equal(fi.FullName, fi2.FullName); + } +} diff --git a/tests/QuickIO.UnitTests/QuickIO_File_Copy_Tests.cs b/tests/QuickIO.UnitTests/QuickIO_File_Copy_Tests.cs new file mode 100644 index 0000000..43ea77f --- /dev/null +++ b/tests/QuickIO.UnitTests/QuickIO_File_Copy_Tests.cs @@ -0,0 +1,30 @@ +using Xunit; + +namespace SchwabenCode.QuickIO.UnitTests; + +public class QuickIO_File_Copy_Tests +{ + [Fact] + public void File_Copy_Test() + { + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + + Assert.True(File.Exists(file), "Created test file does not exists (SystemIO)."); + + string newFileName = "COPY" + Path.GetFileName( file ); + QuickIOFile.CopyToDirectory(file, Path.GetDirectoryName(file)!, newFileName); + + Assert.True(File.Exists(Path.Combine(Path.GetDirectoryName(file)!, newFileName)), "File does not exist after delete."); + } + + [Fact] + public void File_Copy_Test_TargetNotExists() + { + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + string targetFileName = Path.Combine( prov.GetTestFileDirectory( ), prov.GetRandomTestFileName(), "TestFileName" ); + + QuickIOFile.Copy(file, targetFileName); + } +} diff --git a/tests/QuickIO.UnitTests/QuickIO_File_Tests.cs b/tests/QuickIO.UnitTests/QuickIO_File_Tests.cs new file mode 100644 index 0000000..3a55e78 --- /dev/null +++ b/tests/QuickIO.UnitTests/QuickIO_File_Tests.cs @@ -0,0 +1,215 @@ +using Xunit; + +namespace SchwabenCode.QuickIO.UnitTests; + + +public class QuickIO_File_Tests +{ + [Fact] + public void File_AppendAllText_Test() + { + string test = "Test text"; + + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + + Assert.True(QuickIOFile.Exists(file), "Created test file does not exists."); + + QuickIOFile.WriteAllText(file, test); + Assert.Equal(test, QuickIOFile.ReadAllText(file)); + + // Append + string appended = " Ben"; + QuickIOFile.AppendAllText(file, appended); + Assert.Equal(test + appended, QuickIOFile.ReadAllText(file)); + } + + + [Fact] + public void File_AppendAllLines_Test() + { + string[] test = ["Line0", "Line1", "Line2"]; + + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + + Assert.True(QuickIOFile.Exists(file), "Created test file does not exists."); + + QuickIOFile.WriteAllLines(file, test); + List result = QuickIOFile.ReadAllLines( file ).ToList( ); + Assert.Equal(test[0], result[0]); + Assert.Equal(test[1], result[1]); + + // Append + QuickIOFile.AppendAllLines(file, new List() { test[2] }); + Assert.Equal(test[0], result[0]); + Assert.Equal(test[1], result[1]); + Assert.Equal(test[2], result[2]); + } + + [Fact] + public void File_Create_With_Path_Test() + { + string testPath = Path.GetFullPath( Path.GetRandomFileName( ) ); + QuickIOFile.Create(testPath); + + Assert.True(File.Exists(testPath)); + } + + [Fact] + public void File_Delete_Test() + { + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + + Assert.True(File.Exists(file), "Created test file does not exists (SystemIO)."); + + + QuickIOFile.Delete(file); + + Assert.False(File.Exists(file), "File still exists after delete."); + } + [Fact] + public void File_Readonly_Delete_Test() + { + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + + Assert.True(File.Exists(file), "Created test file does not exists (SystemIO)."); + + File.SetAttributes(file, FileAttributes.ReadOnly); + + FileAttributes attributes = File.GetAttributes( file ); + Assert.True(attributes.HasFlag(FileAttributes.ReadOnly)); + + QuickIOFile.Delete(file); + + Assert.False(File.Exists(file), "File still exists after delete."); + } + + + [Fact] + public void File_Exists_Test() + { + string testPathMissing = Path.GetFullPath( Path.GetRandomFileName( ) ); + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + + Assert.True(File.Exists(file), "1 Created test file does not exists (SystemIO)."); + Assert.True(QuickIOFile.Exists(file), "2 Created test file does not exists (QuickIO)."); + + Assert.False(File.Exists(testPathMissing), "3 Created test file exists (SystemIO)."); + Assert.False(QuickIOFile.Exists(testPathMissing), "4 Created test file exists (QuickIO)."); + } + + [Fact] + public void File_MoveTest_SimplePaths() + { + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + + string targetFile = Path.Combine( Path.GetDirectoryName( file )!, "MOVED_" + Path.GetFileName( file ) ); + + Assert.True(QuickIOFile.Exists(file), "Created test file does not exists."); + + QuickIOFile.Move(file, targetFile); + List allFiles = QuickIODirectory.EnumerateFilePaths( Path.GetDirectoryName( file )!, QuickIOPatternConstants.All, SearchOption.TopDirectoryOnly ).ToList( ); + + Assert.True(allFiles.All(x => !x.Equals(file, StringComparison.InvariantCultureIgnoreCase)), "Created test file still exists."); + Assert.False(allFiles.Any(x => x.Equals(file, StringComparison.InvariantCultureIgnoreCase)), "Created test file not moved."); + + } + + [Fact] + public void File_MoveTest_PathInfo() + { + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + QuickIOFileInfo info = new( file ); + + Assert.True(QuickIOFile.Exists(info), "Created test file does not exists."); + + QuickIOFile.Move(info.PathInfo, info.PathInfo.Parent!); + } + + + [Fact] + public void File_OpenTest_Read() + { + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + + Assert.True(QuickIOFile.Exists(file), "Created test file does not exists."); + + using FileStream fileStream = QuickIOFile.Open(file, FileMode.Open, FileAccess.Read); + Assert.True(fileStream.CanRead); + Assert.False(fileStream.CanWrite); + } + + [Fact] + public void File_OpenTest_Write() + { + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + + Assert.True(QuickIOFile.Exists(file), "Created test file does not exists."); + + using FileStream fileStream = QuickIOFile.Open(file, FileMode.Open, FileAccess.ReadWrite); + Assert.True(fileStream.CanRead); + Assert.True(fileStream.CanWrite); + } + + [Fact] + public void File_Write_And_Read_AllBytesTest() + { + byte[] test = [64, 72]; + + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + + Assert.True(QuickIOFile.Exists(file), "Created test file does not exists."); + + QuickIOFile.WriteAllBytes(file, test); + + List result = QuickIOFile.ReadAllBytes( file ).ToList( ); + + Assert.Equal(test[0], result[0]); + Assert.Equal(test[1], result[1]); + } + + [Fact] + public void File_Write_And_Read_AllLinesTest() + { + string[] test = ["Zeile0", "Zeile1"]; + + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + + Assert.True(QuickIOFile.Exists(file), "Created test file does not exists."); + + QuickIOFile.WriteAllLines(file, test); + + List result = QuickIOFile.ReadAllLines( file ).ToList( ); + + Assert.Equal(test[0], result[0]); + Assert.Equal(test[1], result[1]); + } + + + [Fact] + public void File_Write_and_Read_AllTextTest() + { + string test = "Test text"; + + using RandomTestFileProvider prov = new(); + string file = prov.CreateRandomTestFile( ); + + Assert.True(QuickIOFile.Exists(file), "Created test file does not exists."); + + QuickIOFile.WriteAllText(file, test); + + string result = QuickIOFile.ReadAllText( file ); + + Assert.Equal(test, result); + } +} diff --git a/tests/QuickIO.UnitTests/QuickIO_PathInfo_Tests.cs b/tests/QuickIO.UnitTests/QuickIO_PathInfo_Tests.cs new file mode 100644 index 0000000..4bd3d71 --- /dev/null +++ b/tests/QuickIO.UnitTests/QuickIO_PathInfo_Tests.cs @@ -0,0 +1,44 @@ +using FluentAssertions; +using Xunit; + +namespace SchwabenCode.QuickIO.UnitTests; + + +public class QuickIO_PathInfo_Tests +{ + [Fact] + public void QuickIOPathInfo_Create_Object_CTor_LocalFile_Test() + { + QuickIOPathInfo pathInfo = new( @"C:\temp\file.txt" ); + + pathInfo.FullName.Should().Be(@"C:\temp\file.txt"); + pathInfo.FullNameUnc.Should().Be(QuickIOPath.UncLocalPathPrefix + @"C:\temp\file.txt"); + } + + [Fact] + public void QuickIOPathInfo_Create_Object_CTor_LocalFolder_Test() + { + QuickIOPathInfo pathInfo = new( @"C:\temp" ); + + pathInfo.FullName.Should().Be(@"C:\temp"); + pathInfo.FullNameUnc.Should().Be(QuickIOPath.UncLocalPathPrefix + @"C:\temp"); + } + + [Fact] + public void QuickIOPathInfo_Create_Object_CTor_ShareFile_Test() + { + QuickIOPathInfo pathInfo = new( @"\\server\share\file.txt" ); + + pathInfo.FullName.Should().Be(@"\\server\share\file.txt"); + pathInfo.FullNameUnc.Should().Be(QuickIOPath.UncSharePathPrefix + @"server\share\file.txt"); + } + + [Fact] + public void QuickIOPathInfo_Create_Object_CTor_ShareFolder_Test() + { + QuickIOPathInfo pathInfo = new( @"\\server\share" ); + + pathInfo.FullName.Should().Be(@"\\server\share"); + pathInfo.FullNameUnc.Should().Be(QuickIOPath.UncSharePathPrefix + @"server\share"); + } +} diff --git a/tests/QuickIO.UnitTests/QuickIO_Path_Tests.cs b/tests/QuickIO.UnitTests/QuickIO_Path_Tests.cs new file mode 100644 index 0000000..a6dc5dd --- /dev/null +++ b/tests/QuickIO.UnitTests/QuickIO_Path_Tests.cs @@ -0,0 +1,501 @@ +using Xunit; + +namespace SchwabenCode.QuickIO.UnitTests; + +public class QuickIO_Path_Tests +{ + [Fact] + public void Path_GetRootFromSimplePathTest_HaveToSucceed() + { + Assert.Equal(@"C:\", QuickIOPath.GetRootFromLocalPath(@"C:\test\path", QuickIOPathLocation.Local)); + Assert.Equal(@"C:\", QuickIOPath.GetRootFromLocalPath(@"C:\test\path\dsadasd", QuickIOPathLocation.Local)); + Assert.Equal(@"C:\", QuickIOPath.GetRootFromLocalPath(@"C:\test\path\sa\dd\s.jpf", QuickIOPathLocation.Local)); + Assert.Equal(@"C:\", QuickIOPath.GetRootFromLocalPath(@"C:\test\path\", QuickIOPathLocation.Local)); + Assert.Equal(@"C:\", QuickIOPath.GetRootFromLocalPath(@"C:\", QuickIOPathLocation.Local)); + + + Assert.Equal(@"\\server\share", QuickIOPath.GetRootFromLocalPath(@"\\server\share\s\\s\sss\ssss", QuickIOPathLocation.Share)); + Assert.Equal(@"\\server\share", QuickIOPath.GetRootFromLocalPath(@"\\server\share\s\\ssss", QuickIOPathLocation.Share)); + Assert.Equal(@"\\server\share", QuickIOPath.GetRootFromLocalPath(@"\\server\share", QuickIOPathLocation.Share)); + Assert.Equal(@"\\server\share", QuickIOPath.GetRootFromLocalPath(@"\\server\share\", QuickIOPathLocation.Share)); + } + + [Fact] + public void Path_TestPathPrefixes() + { + Assert.Equal("", QuickIOPath.RegularLocalPathPrefix); + Assert.Equal(@"\\", QuickIOPath.RegularSharePathPrefix); + Assert.Equal(@"\\?\", QuickIOPath.UncLocalPathPrefix); + Assert.Equal(@"\\?\UNC\", QuickIOPath.UncSharePathPrefix); + } + + [Fact] + public void Path_ToRegularPathTest() + { + Assert.Equal(@"C:\", QuickIOPath.ToRegularPath(@"\\?\C:\")); + Assert.Equal(@"C:\", QuickIOPath.ToRegularPath(@"C:\")); + + Assert.Equal(@"\\server\share\folder", QuickIOPath.ToRegularPath(@"\\server\share\folder")); + Assert.Equal(@"\\server\share\folder", QuickIOPath.ToRegularPath(@"\\?\UNC\server\share\folder")); + } + + [Fact] + public void Path_ToUncPathTest() + { + Assert.Equal(@"\\?\C:\", QuickIOPath.ToUncPath(@"\\?\C:\")); + Assert.Equal(@"\\?\C:\", QuickIOPath.ToUncPath(@"C:\")); + + Assert.Equal(@"\\?\UNC\server\share\folder", QuickIOPath.ToUncPath(@"\\server\share\folder")); + Assert.Equal(@"\\?\UNC\server\share\folder", QuickIOPath.ToUncPath(@"\\?\UNC\server\share\folder")); + } + + [Fact] + public void Path_GetFullPath_Equal_Test() + { + Assert.Equal(Path.GetFullPath("Ben"), QuickIOPath.GetFullPath("Ben")); + } + + [Fact] + public void GetFullPathInfo_Equal_Test() + { + Assert.Equal(Path.GetFullPath("Ben"), QuickIOPath.GetFullPathInfo("Ben").FullName); + } + + [Fact] + public void Path_Const_LocalRegularPrefix_Test() + { + Assert.Equal(QuickIOPath.RegularLocalPathPrefix, string.Empty); + } + [Fact] + public void Path_Const_LocalUncPrefix_Test() + { + Assert.Equal(QuickIOPath.UncLocalPathPrefix, @"\\?\"); + } + [Fact] + public void Path_Const_ShareRegularPrefix_Test() + { + Assert.Equal(QuickIOPath.RegularSharePathPrefix, @"\\"); + } + [Fact] + public void Path_Const_ShareUncPrefix_Test() + { + Assert.Equal(QuickIOPath.UncSharePathPrefix, @"\\?\UNC\"); + } + + [Fact] + public void Path_ToLocalLocalRegular_Folder_Test() + { + const string testPath = @"\\?\C:\temp"; + const string shouldBe = @"C:\temp"; + string convertedPath = QuickIOPath.ToLocalRegularPath( testPath ); + Assert.Equal(shouldBe, convertedPath); + } + [Fact] + public void Path_ToLocalLocalRegular_File_Test() + { + const string testPath = @"\\?\C:\temp\file.txt"; + const string shouldBe = @"C:\temp\file.txt"; + string convertedPath = QuickIOPath.ToLocalRegularPath( testPath ); + Assert.Equal(shouldBe, convertedPath); + } + + [Fact] + public void Path_ToShareRegularPath_Folder_Test() + { + const string testPath = @"\\?\UNC\server\share"; + const string shouldBe = @"\\server\share"; + string convertedPath = QuickIOPath.ToShareRegularPath( testPath ); + Assert.Equal(shouldBe, convertedPath); + } + + [Fact] + public void Path_ToShareRegularPath_File_Test() + { + const string testPath = @"\\?\UNC\server\share\file.txt"; + const string shouldBe = @"\\server\share\file.txt"; + string convertedPath = QuickIOPath.ToShareRegularPath( testPath ); + Assert.Equal(shouldBe, convertedPath); + } + + + [Fact] + public void Path_Combination_Test() + { + string shouldBe = Path.Combine( @"C:\temp\", @"\test\folder" ); + string reference = QuickIOPath.Combine( @"C:\temp\", @"\test\folder" ); + Assert.Equal(shouldBe, reference); + } + + [Fact] + public void Path_ToShareUncPath_Folder_Test() + { + const string testPath = @"\\server\share"; + const string shouldBe = @"\\?\UNC\server\share"; + string convertedPath = QuickIOPath.ToShareUncPath( testPath ); + Assert.Equal(shouldBe, convertedPath); + } + + [Fact] + public void Path_ToShareUncPath_File_Test() + { + const string testPath = @"\\server\share\file.txt"; + const string shouldBe = @"\\?\UNC\server\share\file.txt"; + string convertedPath = QuickIOPath.ToShareUncPath( testPath ); + Assert.Equal(shouldBe, convertedPath); + } + + + [Fact] + public void Path_ToLocalUncPath_Folder_Test() + { + const string testPath = @"C:\temp"; + const string shouldBe = @"\\?\C:\temp"; + string convertedPath = QuickIOPath.ToLocalUncPath( testPath ); + Assert.Equal(shouldBe, convertedPath); + } + + [Fact] + public void Path_ToLocalUncPath_File_Test() + { + const string testPath = @"C:\temp\file.txt"; + const string shouldBe = @"\\?\C:\temp\file.txt"; + string convertedPath = QuickIOPath.ToLocalUncPath( testPath ); + Assert.Equal(shouldBe, convertedPath); + } + + [Fact] + public void Path_GetName_Invalid_Test() + { + string r = QuickIOPath.GetName( @"peterpan" ); + Assert.Equal("peterpan", r); + } + + [Fact] + public void Path_GetName_SimpleName_Test() + { + string r = QuickIOPath.GetName( @"peter\pan" ); + Assert.Equal("pan", r); + } + + [Fact] + public void Path_GetParent1_Test() + { + string fullname1 = Path.GetFullPath( @"peter\pan" ); + string parent1 = new DirectoryInfo( fullname1 ).Parent!.FullName; + Assert.Equal(parent1, QuickIOPath.GetParentPath(fullname1)); + + + } + [Fact] + public void Path_GetParent2_Test() + { + string expected = @"C:\temp\folder\folder\parent"; + string fullpath = expected + @"\name"; + + Assert.Equal(expected, QuickIOPath.GetParentPath(fullpath)); + } + + [Fact] + public void Path_GetRoot_Test() + { + string expected = @"C:\"; + string fullpath = expected + @"temp\folder\folder\parent\name"; + + Assert.Equal(expected, QuickIOPath.GetRoot(fullpath)); + } + + + [Fact] + public void Path_IsLocalRegularPath_Test() + { + Assert.True(QuickIOPath.IsLocalRegularPath(@"C:\"), "1 failed"); + Assert.True(QuickIOPath.IsLocalRegularPath(@"c:\"), "2 failed"); + + + Assert.True(QuickIOPath.IsLocalRegularPath(@"C:\dsad"), "5 failed"); + Assert.True(QuickIOPath.IsLocalRegularPath(@"c:\dsad 0s\sadsad\d"), "6 failed"); + + Assert.False(QuickIOPath.IsLocalRegularPath(@"4:\"), "3 failed"); + Assert.False(QuickIOPath.IsLocalRegularPath(@"as:\dd"), "4 failed"); + } + + [Fact] + public void Path_IsLocalUncPath_Test() + { + Assert.True(QuickIOPath.IsLocalUncPath(@"\\?\C:\"), "1 failed"); + Assert.True(QuickIOPath.IsLocalUncPath(@"\\?\c:\"), "2 failed"); + + + Assert.True(QuickIOPath.IsLocalUncPath(@"\\?\C:\dsad"), "5 failed"); + Assert.True(QuickIOPath.IsLocalUncPath(@"\\?\c:\dsad 0s\sadsad\d"), "6 failed"); + + Assert.False(QuickIOPath.IsLocalUncPath(@"\\?\4:\"), "3 failed"); + Assert.False(QuickIOPath.IsLocalUncPath(@"\\?\as:\dd"), "4 failed"); + } + + [Fact] + public void Path_IsShareRegularPath_Test() + { + Assert.True(QuickIOPath.IsShareRegularPath(@"\\server\name"), "1 failed"); + Assert.True(QuickIOPath.IsShareRegularPath(@"\\servEr\nAme"), "2 failed"); + + Assert.True(QuickIOPath.IsShareRegularPath(@"\\server\name\folder"), "5 failed"); + Assert.True(QuickIOPath.IsShareRegularPath(@"\\server\name\folder\folder\file.txt"), "6 failed"); + + Assert.False(QuickIOPath.IsShareRegularPath(@"f\\server\name\folder"), "3 failed"); + Assert.False(QuickIOPath.IsShareRegularPath(@"\server\name\folder"), "4 failed"); + Assert.False(QuickIOPath.IsShareRegularPath(@"server\name\folder"), "5 failed"); + Assert.False(QuickIOPath.IsShareRegularPath(@"\UNC\?\server\name\folder"), "7 failed"); + } + + [Fact] + public void Path_IsShareUncPath_Test() + { + Assert.True(QuickIOPath.IsShareUncPath(@"\\?\UNC\server\name"), "1 failed"); + Assert.True(QuickIOPath.IsShareUncPath(@"\\?\UNC\servEr\nAme"), "2 failed"); + + + Assert.True(QuickIOPath.IsShareUncPath(@"\\?\UNC\server\name\folder"), "5 failed"); + Assert.True(QuickIOPath.IsShareUncPath(@"\\?\UNC\server\name\folder\folder\file.txt"), "6 failed"); + + Assert.False(QuickIOPath.IsShareUncPath(@"f\\?\UNC\server\name\folder"), "3 failed"); + Assert.False(QuickIOPath.IsShareUncPath(@"\\server\name\folder"), "4 failed"); + Assert.False(QuickIOPath.IsShareUncPath(@"server\name\folder"), "5 failed"); + } + + [Fact] + public void Path_TryParse_Test1() + { + bool done = QuickIOPath.TryParsePath( @"C:\", out QuickIOParsePathResult? result ); + + Assert.True(done); + Assert.NotNull(result); + + Assert.True(result.IsRoot); + Assert.Equal(@"C:\", result.FullName); + Assert.Equal(@"\\?\C:\", result.FullNameUnc); + Assert.Null(result.Name); + Assert.Null(result.ParentPath); + Assert.Equal(QuickIOPathLocation.Local, result.PathLocation); + Assert.Equal(QuickIOPathType.Regular, result.PathType); + Assert.Null(result.RootPath); + } + + [Fact] + public void Path_ParseLocalRegularPath_Test1() + { + bool done = QuickIOPath.TryParseLocalRegularPath( @"C:\", out QuickIOParsePathResult? result ); + + Assert.True(done); + Assert.NotNull(result); + + Assert.True(result.IsRoot, "IsRoot failed"); + Assert.Equal(@"C:\", result.FullName); + Assert.Equal(@"\\?\C:\", result.FullNameUnc); + Assert.Null(result.Name); + Assert.Null(result.ParentPath); + Assert.Equal(QuickIOPathLocation.Local, result.PathLocation); + Assert.Equal(QuickIOPathType.Regular, result.PathType); + Assert.Null(result.RootPath); + } + + [Fact] + public void Path_TryParse_Test2() + { + bool done = QuickIOPath.TryParsePath( @"C:\peter\pan", out QuickIOParsePathResult? result ); + + Assert.True(done); + Assert.NotNull(result); + + Assert.False(result.IsRoot); + Assert.Equal(@"C:\peter\pan", result.FullName); + Assert.Equal(@"\\?\C:\peter\pan", result.FullNameUnc); + Assert.Equal("pan", result.Name); + Assert.Equal(@"C:\peter", result.ParentPath); + Assert.Equal(QuickIOPathLocation.Local, result.PathLocation); + Assert.Equal(QuickIOPathType.Regular, result.PathType); + Assert.Equal(@"C:\", result.RootPath); + } + + [Fact] + public void Path_ParseLocalRegularPath_Test2() + { + bool done = QuickIOPath.TryParseLocalRegularPath( @"C:\peter\pan", out QuickIOParsePathResult? result ); + + Assert.True(done); + Assert.NotNull(result); + + Assert.False(result.IsRoot); + Assert.Equal(@"C:\peter\pan", result.FullName); + Assert.Equal(@"\\?\C:\peter\pan", result.FullNameUnc); + Assert.Equal("pan", result.Name); + Assert.Equal(@"C:\peter", result.ParentPath); + Assert.Equal(QuickIOPathLocation.Local, result.PathLocation); + Assert.Equal(QuickIOPathType.Regular, result.PathType); + Assert.Equal(@"C:\", result.RootPath); + } + + [Fact] + public void Path_ParseLocalRegularPath_Test3() + { + bool done = QuickIOPath.TryParseLocalRegularPath( @"C:\peter\pan\file.txt", out QuickIOParsePathResult? result ); + + Assert.True(done); + Assert.NotNull(result); + + Assert.False(result.IsRoot, "IsRoot failed"); + Assert.Equal(@"C:\peter\pan\file.txt", result.FullName); + Assert.Equal(@"\\?\C:\peter\pan\file.txt", result.FullNameUnc); + Assert.Equal("file.txt", result.Name); + Assert.Equal(@"C:\peter\pan", result.ParentPath); + Assert.Equal(QuickIOPathLocation.Local, result.PathLocation); + Assert.Equal(QuickIOPathType.Regular, result.PathType); + Assert.Equal(@"C:\", result.RootPath); + } + + [Fact] + public void Path_ParseLocalUncPath_Test1() + { + bool done = QuickIOPath.TryParseLocalUncPath( @"\\?\C:\", out QuickIOParsePathResult? result ); + + Assert.True(done); + Assert.NotNull(result); + + Assert.True(result.IsRoot, "IsRoot failed"); + Assert.Equal(@"C:\", result.FullName); + Assert.Equal(@"\\?\C:\", result.FullNameUnc); + Assert.Null(result.Name); + Assert.Null(result.ParentPath); + Assert.Equal(QuickIOPathLocation.Local, result.PathLocation); + Assert.Equal(QuickIOPathType.UNC, result.PathType); + Assert.Null(result.RootPath); + + } + + [Fact] + public void Path_ParseLocalUncPath_Test2() + { + bool done = QuickIOPath.TryParseLocalUncPath( @"\\?\C:\peter\pan", out QuickIOParsePathResult? result ); + + Assert.True(done); + Assert.NotNull(result); + + Assert.False(result.IsRoot, "IsRoot failed"); + Assert.Equal(@"C:\peter\pan", result.FullName); + Assert.Equal(@"\\?\C:\peter\pan", result.FullNameUnc); + Assert.Equal("pan", result.Name); + Assert.Equal(@"C:\peter", result.ParentPath); + Assert.Equal(QuickIOPathLocation.Local, result.PathLocation); + Assert.Equal(QuickIOPathType.UNC, result.PathType); + Assert.Equal(@"C:\", result.RootPath); + } + + [Fact] + public void Path_ParseLocalUncPath_Test3() + { + bool done = QuickIOPath.TryParseLocalUncPath( @"\\?\C:\peter\pan\file.txt", out QuickIOParsePathResult? result ); + + Assert.True(done); + Assert.NotNull(result); + + Assert.False(result.IsRoot, "IsRoot failed"); + Assert.Equal(@"C:\peter\pan\file.txt", result.FullName); + Assert.Equal(@"\\?\C:\peter\pan\file.txt", result.FullNameUnc); + Assert.Equal("file.txt", result.Name); + Assert.Equal(@"C:\peter\pan", result.ParentPath); + Assert.Equal(QuickIOPathLocation.Local, result.PathLocation); + Assert.Equal(QuickIOPathType.UNC, result.PathType); + Assert.Equal(@"C:\", result.RootPath); + } + + + [Fact] + public void Path_ParseShareRegularPath_Test1() + { + bool done = QuickIOPath.TryParseShareRegularPath( @"\\server\share", out QuickIOParsePathResult? result ); + + Assert.True(done); + Assert.NotNull(result); + + Assert.True(result.IsRoot, "IsRoot failed"); + Assert.Equal(@"\\server\share", result.FullName); + Assert.Equal(@"\\?\UNC\server\share", result.FullNameUnc); + Assert.Null(result.Name); + Assert.Null(result.ParentPath); + Assert.Equal(QuickIOPathLocation.Share, result.PathLocation); + Assert.Equal(QuickIOPathType.Regular, result.PathType); + Assert.Null(result.RootPath); + } + + [Fact] + public void Path_ParseShareRegularPath_Test2() + { + bool done = QuickIOPath.TryParseShareRegularPath( @"\\?\UNC\server\share", out QuickIOParsePathResult? result ); + + Assert.False(done); + Assert.Null(result); + } + + [Fact] + public void Path_ParseShareRegularPath_Test3() + { + bool done = QuickIOPath.TryParseShareRegularPath( @"\\server\share\folder\parent\file.txt", out QuickIOParsePathResult? result ); + + Assert.True(done); + Assert.NotNull(result); + + Assert.False(result.IsRoot, "IsRoot failed"); + Assert.Equal(@"\\server\share\folder\parent\file.txt", result.FullName); + Assert.Equal(@"\\?\UNC\server\share\folder\parent\file.txt", result.FullNameUnc); + Assert.Equal("file.txt", result.Name); + Assert.Equal(@"\\server\share\folder\parent", result.ParentPath); + Assert.Equal(QuickIOPathLocation.Share, result.PathLocation); + Assert.Equal(QuickIOPathType.Regular, result.PathType); + Assert.Equal(@"\\server\share", result.RootPath); + } + + [Fact] + public void Path_ParseShareUncPath_Test1() + { + bool done = QuickIOPath.TryParseShareUncPath( @"\\?\UNC\server\share", out QuickIOParsePathResult? result ); + + Assert.True(done); + Assert.NotNull(result); + + Assert.True(result.IsRoot, "IsRoot failed"); + Assert.Equal(@"\\server\share", result.FullName); + Assert.Equal(@"\\?\UNC\server\share", result.FullNameUnc); + Assert.Null(result.Name); + Assert.Null(result.ParentPath); + Assert.Equal(QuickIOPathLocation.Share, result.PathLocation); + Assert.Equal(QuickIOPathType.UNC, result.PathType); + Assert.Null(result.RootPath); + } + + [Fact] + public void Path_ParseShareUncPath_Test2() + { + bool done = QuickIOPath.TryParseShareUncPath( @"\\server\share", out _ ); + + Assert.False(done); + } + + [Fact] + public void Path_ParseShareUncPath_Test3() + { + bool done = QuickIOPath.TryParseShareUncPath( @"\\?\UNC\server\share\folder\parent\file.txt", + out QuickIOParsePathResult? result ); + + Assert.True(done); + Assert.NotNull(result); + + Assert.False(result.IsRoot, "IsRoot failed"); + Assert.Equal(@"\\server\share\folder\parent\file.txt", result.FullName); + Assert.Equal(@"\\?\UNC\server\share\folder\parent\file.txt", result.FullNameUnc); + Assert.Equal("file.txt", result.Name); + Assert.Equal(@"\\server\share\folder\parent", result.ParentPath); + Assert.Equal(QuickIOPathLocation.Share, result.PathLocation); + Assert.Equal(QuickIOPathType.UNC, result.PathType); + Assert.Equal(@"\\server\share", result.RootPath); + } +} diff --git a/tests/QuickIO.UnitTests/QuickIO_Patterns_Tests.cs b/tests/QuickIO.UnitTests/QuickIO_Patterns_Tests.cs new file mode 100644 index 0000000..dcbe32d --- /dev/null +++ b/tests/QuickIO.UnitTests/QuickIO_Patterns_Tests.cs @@ -0,0 +1,27 @@ +using System.Text.RegularExpressions; +using Xunit; + +namespace SchwabenCode.QuickIO.UnitTests; + +public class QuickIO_Patterns_Tests +{ + [Fact] + public void Pattern_ShareRoot_Test() + { + // Name + Assert.True(Regex.IsMatch(@"\\server\share", QuickIOPatterns.GetStrict(QuickIOPatterns.RegularShareRootPattern), RegexOptions.IgnoreCase), "1 failed"); + + // IP + Assert.True(Regex.IsMatch(@"\\1:2:3:4:5:6:7:8\share\", QuickIOPatterns.GetStrict(QuickIOPatterns.RegularShareRootPattern)), "2 failed"); + Assert.True(Regex.IsMatch(@"\\1080:0:0:0:8:800:200C:417A\share", QuickIOPatterns.GetStrict(QuickIOPatterns.RegularShareRootPattern)), "3 failed"); + Assert.True(Regex.IsMatch(@"\\255.255.255.0\share", QuickIOPatterns.GetStrict(QuickIOPatterns.RegularShareRootPattern)), "4 failed"); + Assert.True(Regex.IsMatch(@"\\192.168.1.19\share", QuickIOPatterns.GetStrict(QuickIOPatterns.RegularShareRootPattern)), "5 failed"); + Assert.True(Regex.IsMatch(@"\\::1\share", QuickIOPatterns.GetStrict(QuickIOPatterns.RegularShareRootPattern)), "6 failed"); + + Assert.True(Regex.IsMatch(@"\\seRver\share", QuickIOPatterns.GetStrict(QuickIOPatterns.RegularShareRootPattern)), "8 failed"); + Assert.True(Regex.IsMatch(@"\\server\share\", QuickIOPatterns.GetStrict(QuickIOPatterns.RegularShareRootPattern)), "9 failed"); + + Assert.False(Regex.IsMatch(@"\\server", QuickIOPatterns.GetStrict(QuickIOPatterns.RegularShareRootPattern)), "10 failed"); + Assert.False(Regex.IsMatch(@"\\server\share\ssd", QuickIOPatterns.GetStrict(QuickIOPatterns.RegularShareRootPattern)), "11 failed"); + } +} diff --git a/tests/QuickIO.UnitTests/QuickIO_Transfer_CopyJob.cs b/tests/QuickIO.UnitTests/QuickIO_Transfer_CopyJob.cs new file mode 100644 index 0000000..5c932ee --- /dev/null +++ b/tests/QuickIO.UnitTests/QuickIO_Transfer_CopyJob.cs @@ -0,0 +1,17 @@ +using SchwabenCode.QuickIO.Transfer; +using Xunit; + +namespace SchwabenCode.QuickIO.UnitTests; + +public class QuickIO_Transfer_CopyJob +{ + [Fact] + public void TestCopyJob_1() + { + string testFile = Path.GetFullPath( @"TestFiles\Test.txt" ); + string target = @"D:\testfile.txt"; + + QuickIOTransferFileCopyJob copyJob = new( testFile, target, 65535, overwrite: true ); + copyJob.Run(); + } +} diff --git a/tests/QuickIO.UnitTests/RandomTestFileProvider.cs b/tests/QuickIO.UnitTests/RandomTestFileProvider.cs new file mode 100644 index 0000000..000af10 --- /dev/null +++ b/tests/QuickIO.UnitTests/RandomTestFileProvider.cs @@ -0,0 +1,50 @@ +namespace SchwabenCode.QuickIO.UnitTests; + +public class RandomTestFileProvider : IDisposable +{ + public IList Files { get; private set; } + + public string GetTestFileDirectory() + { + return Path.GetFullPath("TestFiles\\"); + } + + public string GetRandomTestFileName() + { + return Path.Combine(GetTestFileDirectory(), Path.GetRandomFileName()); + } + + public string CreateRandomTestFile() + { + string testPath = Path.Combine( GetTestFileDirectory( ), Path.GetRandomFileName( ) ); + QuickIOFile.Create(testPath); + + return testPath; + } + + public RandomTestFileProvider() + { + Files = new List(); + } + + public void Dispose() + { + List tempFiles = Files.ToList( ); + + if (Files != null) + { + foreach (string? file in tempFiles) + { + try + { + File.Delete(file); + _ = Files.Remove(file); + } + catch (Exception) + { + // I dont care + } + } + } + } +} \ No newline at end of file diff --git a/tests/QuickIO.UnitTests/TestFiles/DirTimeTest/File.txt b/tests/QuickIO.UnitTests/TestFiles/DirTimeTest/File.txt new file mode 100644 index 0000000..1ad72d7 --- /dev/null +++ b/tests/QuickIO.UnitTests/TestFiles/DirTimeTest/File.txt @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace QuickIOTests.UnitTests.TestFiles.DirTimeTest +{ + class File + { + } +} diff --git a/tests/QuickIO.UnitTests/TestFiles/HiddenFile.txt b/tests/QuickIO.UnitTests/TestFiles/HiddenFile.txt new file mode 100644 index 0000000..7f36fb6 --- /dev/null +++ b/tests/QuickIO.UnitTests/TestFiles/HiddenFile.txt @@ -0,0 +1 @@ +Hidden \ No newline at end of file diff --git a/tests/QuickIO.UnitTests/TestFiles/Overwrites/Test.txt b/tests/QuickIO.UnitTests/TestFiles/Overwrites/Test.txt new file mode 100644 index 0000000..ee847dd --- /dev/null +++ b/tests/QuickIO.UnitTests/TestFiles/Overwrites/Test.txt @@ -0,0 +1,4 @@ +Hi +I'm a +Test +File \ No newline at end of file diff --git a/tests/QuickIO.UnitTests/TestFiles/Overwrites/TestDir/Test.txt b/tests/QuickIO.UnitTests/TestFiles/Overwrites/TestDir/Test.txt new file mode 100644 index 0000000..ee847dd --- /dev/null +++ b/tests/QuickIO.UnitTests/TestFiles/Overwrites/TestDir/Test.txt @@ -0,0 +1,4 @@ +Hi +I'm a +Test +File \ No newline at end of file diff --git a/tests/QuickIO.UnitTests/TestFiles/ReadonlyFile.txt b/tests/QuickIO.UnitTests/TestFiles/ReadonlyFile.txt new file mode 100644 index 0000000..3db1f38 --- /dev/null +++ b/tests/QuickIO.UnitTests/TestFiles/ReadonlyFile.txt @@ -0,0 +1 @@ +Readonly \ No newline at end of file diff --git a/tests/QuickIO.UnitTests/TestFiles/Test.txt b/tests/QuickIO.UnitTests/TestFiles/Test.txt new file mode 100644 index 0000000..ee847dd --- /dev/null +++ b/tests/QuickIO.UnitTests/TestFiles/Test.txt @@ -0,0 +1,4 @@ +Hi +I'm a +Test +File \ No newline at end of file diff --git a/tests/QuickIO.UnitTests/TransferCopyJob_Tests.cs b/tests/QuickIO.UnitTests/TransferCopyJob_Tests.cs new file mode 100644 index 0000000..032c756 --- /dev/null +++ b/tests/QuickIO.UnitTests/TransferCopyJob_Tests.cs @@ -0,0 +1,56 @@ +//using FluentAssertions; +//using Moq; +//using SchwabenCode.QuickIO; +//using SchwabenCode.QuickIO.Transfer; +//using Xunit; + +//namespace SchwabenCode.QuickIOTests.UnitTests; +// TODO +//public class TransferCopyJob_Tests +//{ +// [Fact] +// public void Test_Ctor1() +// { +// Mock observerMock = new( ); + +// string targetFile = @"C:\temp\qio_target\file.txt"; + +// IQuickIOTransferObserver observer = observerMock.Object; +// QuickIOTransferFileCopyJob job = new( observer, @"C:\temp\qio_source\file.txt", +// targetFile, 1024, false, true, 0 ); + +// try +// { +// job.Run(); +// } +// catch (FileAlreadyExistsException) +// { +// QuickIOFile.Delete(targetFile); +// } + +// job.Run(); +// } + +// [Fact] +// public void Test_QuickIOCanceledException() +// { +// Mock observerMock = new( ); + +// CancellationTokenSource source = new( ); + +// IQuickIOTransferObserver observer = observerMock.Object; +// QuickIOTransferFileCopyJob job = new( observer, @"C:\temp\qio_source\file.txt", +// @"C:\temp\qio_target\file.txt", 1024, false, true, 0, source.Token ); + +// source.Cancel(); + +// Action act = () => job.Run(); +// act.Should().Throw(); +// } + +// [Fact] +// public void Test_Ctor2() +// { +// _ = new QuickIOTransferFileCopyJob(@"C:\temp\qio_source\file.txt", @"C:\temp\qio_target", 1024, false, true, 0); +// } +//} diff --git a/version.json b/version.json new file mode 100644 index 0000000..6d480c7 --- /dev/null +++ b/version.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json", + "version": "3.0", + "assemblyVersion": { + "precision": "revision" // optional. Use when you want a more precise assembly version than the default major.minor. + }, + "nugetPackageVersion": { + "semVer": 1 // optional. Set to either 1 or 2 to control how the NuGet package version string is generated. Default is 1. + }, + "publicReleaseRefSpec": [ + "^refs/heads/main", // we release out of main + "^refs/tags/v\\d+\\.\\d+" // we also release tags starting with vN.N + ], + "cloudBuild": { + "setVersionVariables": true, + "buildNumber": { + "enabled": true + } + }, + "release": { + "branchName": "v{version}", + "versionIncrement": "minor", + "firstUnstableTag": "alpha" + } +} \ No newline at end of file