在c#中使用SharpZibLib在zipfolder中添加没有完整路径的文件

时间:2014-08-19 12:05:12

标签: c# asp.net .net sharpziplib

文件可以轻松添加完整路径,如:

 z.Add(fpaths);

但是我想在下面只添加文件而不是完整路径使用代码,但是错误:

 z.Add(fpaths, filenamed); error is! some invalid arguments 

请查看我的代码,让我知道如何管理此代码

protected void btnAcceptAll_Click(object sender, EventArgs e)
 {
    int count = 0;
    string msg = string.Empty;
    string filenamezip = "FileFolder\\FilesZip.zip";
    string strPathAndQuery = HttpContext.Current.Request.PhysicalApplicationPath;
    string paths = strPathAndQuery + filenamezip;
    ZipFile z = ZipFile.Create(paths);
    z.BeginUpdate();
    foreach (GridViewRow gvrow in gv.Rows)
    {
        CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
        if (chk != null & chk.Checked)
        {
            count++;
            string dirPath = gv.DataKeys[gvrow.RowIndex].Values[3].ToString();
            string fileName = gv.DataKeys[gvrow.RowIndex].Values[1].ToString();
            string filePath = dirPath + "/" + fileName;
            string fpaths = strPathAndQuery + filePath;
            string filenamed = Path.GetFileName(fpaths);
            z.Add(fpaths, filenamed);  //show error
        }
    }
    if (count > 0)
    {
        z.CommitUpdate();
        z.Close();
        BindGrid();
        Session["filenamezip"] = filenamezip;
        ClientScript.RegisterStartupScript(GetType(), "SomeNameForThisScript", "window.open('DownloadZip.aspx', 'DownloadWindow','width=400,height=200');", true);
    }

}

1 个答案:

答案 0 :(得分:0)

尝试使用Path.Combine()代替fpaths的连接:

string fpaths = Path.Combine(strPathAndQuery, filePath);

另外,请确保当您将fpathsfilenamed传递给.Add(string, string)时,null都不会。{/ p>

以下是您尝试使用的方法的来源:

/// <summary>
/// Add a file to the archive.
/// </summary>
/// <param name="fileName">The name of the file to add.</param>
/// <param name="entryName">The name to use for the <see cref="ZipEntry"/> on the Zip file created.</param>
/// <exception cref="ArgumentNullException">Argument supplied is null.</exception>
public void Add(string fileName, string entryName)
{
    if (fileName == null) 
    {
        throw new ArgumentNullException("fileName");
    }

    if ( entryName == null ) 
    {
        throw new ArgumentNullException("entryName");
    }

    CheckUpdating();
    AddUpdate(new ZipUpdate(fileName, EntryFactory.MakeFileEntry(fileName, entryName, true)));
}

由于您可以使用.Add(string)进行添加,因此我怀疑您已将null传递给您尝试使用的超载。