路径不是合法的形式

本文关键字:路径 | 更新日期: 2023-09-27 18:09:59

调试时给出这个错误。Button1是关于zip文件,然后将其从源复制到目标。在delete函数中,它删除创建时间比给定时间更早的文件。注意:我是一个新人,所以如果可能的话,请在你的回答中提供更多的细节。

private void button1_Click(object sender, EventArgs e)
{
    Backup._MAIN takeBackUp = new Backup._MAIN();
    try
    {
        takeBackUp.copyFile(textBox1.Text, textBox2.Text);
         MessageBox.Show("done");  //do stuff
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
private void button2_Click(object sender, EventArgs e)
{
    bool dater;
    string err = "";
    Backup._MAIN formDelete = new Backup._MAIN();
    DateTime dtp = dateTimePicker1.Value;
    dater = formDelete.deleteFiles(textBox3.Text, dtp,out err);
    if (err.Length > 0)
        MessageBox.Show(err);
    else
        MessageBox.Show("Done!");
}

Dll:

public void copyFile(string sSource,string sDestination)
{
    string sourcePath = sSource;
    string targetPath = sDestination;
    Directory.GetFiles(sourcePath,"",SearchOption.AllDirectories);
    string myBackUp="";
    string fileName;
    if (!System.IO.Directory.Exists(targetPath))
    {
        System.IO.Directory.CreateDirectory(targetPath);
    }
    using (ZipFile zip = new ZipFile(targetPath))
    {
        zip.AddDirectory(sourcePath, "");
        zip.Save(myBackUp);
    }
    if (System.IO.Directory.Exists(sourcePath))
    {
        string[] fileList = System.IO.Directory.GetFiles(sourcePath, "*.rar*");
        foreach (string files in fileList)
        {
            // from the path.
            fileName = System.IO.Path.GetFileName(files);
            targetPath = System.IO.Path.Combine(targetPath, fileName);
            System.IO.File.Copy(files, targetPath, true);
        }
    }
}
public bool deleteFiles(string sSource, DateTime dOlder, out string sError)
{
    string path = sSource;
    sError = "";
    try
    {
        string[] fileList = Directory.GetFiles(path);
        foreach ( string fname in fileList )
        {
            if ( File.GetCreationTime(path + fname) <= dOlder )
            {
                File.Delete(path + fname);
            }
        }
        return true;
    }
    catch ( Exception ex )
    {
        sError = ex.ToString();
        return false;
    }
}

路径不是合法的形式

Directory.GetFiles()返回完整的路径名。

但是,考虑您的代码:

string[] fileList = Directory.GetFiles(path);
foreach ( string fname in fileList)
{
    if ( File.GetCreationTime(path + fname) <= dOlder) 

您在执行path + fname时为路径添加了前缀,这将导致无效路径,因为fname已经包含该路径。

如果路径包含驱动器号,例如C:',那么您最终会得到一个像C:'MyDir'C:'MyDir'MyFile.txt这样的路径,这会给您看到的错误。

你只需要做File.GetCreationTime(fname)(和File.Delete()一样。