0

我正在尝试进行编程以进行压缩,.tar 我进行编程的源代码是 Microsoft 主页上提供的示例。但有一个错误。我不知道为什么,一切都和微软主页上的例子一样。

错误是

System.NotSupportedException:不支持给定路径的格式。

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

                 //this directory is what I wanna compress..
            string directoryPath = @"C:\\sfdsf";
            DirectoryInfo directorySelected = new DirectoryInfo(directoryPath);


            foreach (FileInfo filetoCompress in directorySelected.GetFiles())
            {
                Compress(filetoCompress);              
            }
        }

        public static void Compress(FileInfo fileToCompress)
        {
            using (FileStream originalFileStream = fileToCompress.OpenRead())
            {
                if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden)
                    != FileAttributes.Hidden & fileToCompress.Extension != ".tar")
                {
                    using (FileStream compressedFileStream = File.Create(DateTime.Now+ ".tar"))
                    {
                        using (DeflateStream compressionStream = new DeflateStream(compressedFileStream, CompressionMode.Compress))
                        {
                            originalFileStream.CopyTo(compressionStream);

                            MessageBox.Show("Compressed" + fileToCompress.Name + "from" + fileToCompress.Length.ToString() + " to" + compressedFileStream.Length.ToString    () +" bytes.");
                        }
                    }
                }
            }

        }
    }
}
4

1 回答 1

2

删除前面的 at 符号"C:\\sfdsf" 删除其中一个反斜杠:

string directoryPath = "C:\\sfdsf";

或者:

string directoryPath = @"C:\sfdsf";

从您的评论中:

我做了调试。在“使用(FileStream压缩文件流=File.Create(DateTime.Now+“.tar”))”发生了一些事情

将 a 转换DateTime为 a后string,字符串包含斜杠和冒号。斜杠和冒号是文件路径中的无效字符。尝试这个:

string filename = DateTime.Now.ToString.Replace("/", "").Replace(":", "") + ".tar";
using (FileStream compressedFileStream = File.Create(filename))
于 2013-09-28T16:48:12.963 回答