通过FtpWebRequest将文件上传到FTP后无法删除该文件

时间:2013-03-13 08:31:30

标签: c# file-upload ftp

以下是我上传文件的代码:

                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));

                reqFTP.Credentials = new NetworkCredential("****", "*****");
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                reqFTP.KeepAlive = false;
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = true;

                reqFTP.ContentLength = stream.Length;
                // reqFTP.EnableSsl = true; // it's FTPES type of ftp

                int buffLen = 2048;
                byte[] buff = new byte[buffLen];
                int contentLen;

                try
                {
                    Stream ftpStream = reqFTP.GetRequestStream();
                    contentLen = stream.Read(buff, 0, buffLen);
                    while (contentLen != 0)
                    {
                        ftpStream.Write(buff, 0, contentLen);
                        contentLen = stream.Read(buff, 0, buffLen);
                    }

                    ftpStream.Flush();
                    ftpStream.Close();
                    ftpStream.Dispose();

                }
                catch (Exception exc)
                {

                    return false;
                }
                //delete image from local

                stream.Flush();
                stream.Close();
                stream.Dispose();

                DeleteFile();

DeleteFile方法尝试删除上传的文件;但它有一个错误,我的应用程序正在使用该文件,因此它无法删除它。有没有人帮我解决这个问题?!

UPDATE1

private void DeleteFile()
    {
        DirectoryInfo DirInfo = new DirectoryInfo(@"Direectory Contains uploaded file");
        foreach (FileInfo file in DirInfo.GetFiles())
        {
            file.Delete();
        }
    }

1 个答案:

答案 0 :(得分:0)

我假设您要删除本地文件?该错误表明该文件仍在使用中。将代码包含在使用块中的流变量中。