diff --git a/Base16384.Net.csproj b/Base16384.Net.csproj index 16a5f15..3f5a9cf 100644 --- a/Base16384.Net.csproj +++ b/Base16384.Net.csproj @@ -4,7 +4,7 @@ net8.0 enable enable - 1.1.0.0 + 2.0.0.0 @@ -12,5 +12,6 @@ + \ No newline at end of file diff --git a/Helpers.cs b/Helpers.cs new file mode 100644 index 0000000..386a05e --- /dev/null +++ b/Helpers.cs @@ -0,0 +1,19 @@ +namespace ConsoleHelpers; + +public static class Helpers { + public static int WriteToStdOut(Func func, T input, Stream? stdout = null) { + try { + stdout ??= Console.OpenStandardOutput(); + try { + func(input, stdout); + } catch { + return 4; + } finally { + stdout.Dispose(); + } + } catch { + return 3; + } + return 0; + } +} \ No newline at end of file diff --git a/Program.cs b/Program.cs index 083cad9..8a58eae 100644 --- a/Program.cs +++ b/Program.cs @@ -20,28 +20,20 @@ 4. 编解码失败 using var stdin = Console.OpenStandardInput(); if (args.Length == 2 || args[2] == "-") { // Write to stdout - try { - using var stdout = Console.OpenStandardOutput(); - try { - Base16384.EncodeToStream(stdin, stdout); - } catch { - return 4; - } - } catch { - return 3; - } - } else { - // Write to file - FileInfo info = new(args[2]); - Console.Write($" -> {info.Name} ... "); - try { - Base16384.EncodeToNewFile(stdin, info); - } catch { - Console.WriteLine("Failed."); - return 4; - } - Console.WriteLine("Done."); + return Helpers.WriteToStdOut(Base16384.EncodeToStream, stdin); + } + + // Write to file + FileInfo info = new(args[2]); + Console.Write($" -> {info.Name} ... "); + try { + Base16384.EncodeToNewFile(stdin, info); + } catch { + Console.WriteLine("Failed."); + return 4; } + Console.WriteLine("Done."); + } catch { if (args.Length != 2 && args[2] != "-") { Console.WriteLine("Can not open stdin."); @@ -52,19 +44,9 @@ 4. 编解码失败 // Read from file if (args is [.., "-"]) { // Write to stdout - if (!File.Exists(args[1])) { - return 2; - } - try { - using var stdout = Console.OpenStandardOutput(); - try { - Base16384.EncodeFromFileToStream(new(args[1]), stdout); - } catch { - return 4; - } - } catch { - return 3; - } + return !File.Exists(args[1]) + ? 2 + : Helpers.WriteToStdOut(Base16384.EncodeFromFileToStream, new FileInfo(args[1])); } else if (args.Length == 2) { // Write to .decoded file if (!File.Exists(args[1])) {