我正在Visual Studio 2017中制作压缩器/解压缩器控制台程序,我想通过将输入文件拖动到控制台(.txt)来获取文件路径。
我正在为Compress()的inputStream找到正确的路径,但是outPutStream失败并且无法找到文件路径(FileMode.OpenOrCreate!?!),即使该路径是硬编码的。
如果两个变量都经过硬编码,则程序可以正确执行,但是我不明白为什么通过将输入文件从文件拖到控制台并对输出文件进行硬编码来引发System.IO.FileNotFoundException。
....
string outPutFileName = @"C:\bla\bla\bla\bla\gergrgr.gzip";
public static void Compress(string inPath)
{
using (FileStream inputStream = new FileStream(inPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (FileStream outputStream = new FileStream(outPutFileName, FileMode.OpenOrCreate, FileAccess.Write))
{
using (GZipStream gzip = new GZipStream(outputStream, CompressionMode.Compress))
{
inputStream.CopyTo(gzip);
}
}
}
}
static void Main(string[] args)
{
string outPutFileName = @"C:\bla\bla\bla\bla\gergrgr.gzip";
//dummy var, cant find a better way to add '@' to variable set by console.readline
string filePath = @"test";
// info info info....
Console.WriteLine("Drag in txt file");
// Takes the path from dragged in file
string idk = Console.ReadLine();
// instead of of a loop to escape "/", just replace text in filePath
filePath = filePath.Replace("test", idk);
Compress(filePath);
}
答案 0 :(得分:0)
我认为问题实际上是您的应用没有权限写入指定的输出位置。检查docs的FileMode.OpenOrCreate
如果文件访问权限为FileAccess.Write,则需要具有写权限。
以下内容对我有用:
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApp1
{
internal class Program
{
private static readonly string outPutFileName = @"C:<my desktop directory>\gergrgr.gzip";
public static void Compress(string inPath)
{
using (var inputStream = new FileStream(inPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (var outputStream = new FileStream(outPutFileName, FileMode.OpenOrCreate, FileAccess.Write))
{
using (var gzip = new GZipStream(outputStream, CompressionMode.Compress))
{
inputStream.CopyTo(gzip);
}
}
}
}
private static void Main(string[] args)
{
// info info info....
Console.WriteLine("Drag in txt file");
// Takes the path from dragged in file
var filePath = Console.ReadLine();
if (!string.IsNullOrEmpty(filePath))
{
Compress(filePath.Trim('\\', '"'));
}
}
}
}