我正在通过 FTP 上传文件。起初它工作正常,但是当我第二次点击上传按钮时它会抛出错误
The process can not access the file '...' because it is being used by another process
代码如下
using (StreamWriter sw = new StreamWriter(filename, false)) //THIS LINE THROWS ERROR
{
if (dt.Rows.Count > 0)
{
sw.Write("Column1,Column2");
sw.Write(sw.NewLine);
foreach (DataRow dr in dt.Rows)
{
sw.Write(dr["Column1"].ToString());
sw.Write(",");
sw.Write(dr["Column2"].ToString());
sw.Write(",");
}
sw.Close();
sw.Dispose();
}
else
{
sw.Close();
sw.Dispose();
}
}
我正在将文件保存在 csv 中,谁能帮帮我!!为什么我第二次收到此错误?
以下是上传到FTP的代码
public void UploadToFTP()
{
string fileName = "ReportName";
string propfilename = Server.MapPath("~") + fileName + ".csv";
string FtpUserid = null;
string FtpPwd = null;
string sourcePath = string.Empty;
string destPath = string.Empty;
string fName = string.Empty;
FtpUserid = "abc";
FtpPwd = "abc";
fName = fileName + ".csv";
destPath = ConfigurationManager.AppSettings["destipath"].ToString();
destPath = destPath.Insert(destPath.LastIndexOf("/") + 1, fName);
FtpWebRequest requestFileExists = (FtpWebRequest)WebRequest.Create(destPath);
//GET DATA IN CSV
UploadFTPCode(FtpUserid, FtpPwd, sourcePath, destPath, false);
}
private void UploadFTPCode(string FtpUserid, string FtpPwd, string sourcePath, string destPath)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destPath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(FtpUserid, FtpPwd);
request.Proxy = null;
request.UseBinary = false;
request.UsePassive = true;
request.KeepAlive = false;
request.Timeout = 500000;
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(sourcePath);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Dispose();
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Flush();
requestStream.Close();
requestStream.Dispose();
sourceStream.Close();
}
最佳答案
像这样处理文件后尝试调用垃圾回收:
GC.Collect();
关于c# - "The process can not access the file ' ... ' because it is being used by another process"重新创建临时文件以使用 FtpWebRequest 上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44435303/