string path = string.Format("{0}\\{1:D}.txt", m_directoryname, m_EdrFilecount);
try
{
FileInfo myfile = new FileInfo(path);
if (false == myfile.Exists)
{
StreamWriter sw = myfile.CreateText();
sw.Write(edrtext);
sw.Close();
}
else
{
myfile.Delete();
}
}
因为path这个路径的文件已经存在,所以在myfile.Delete()时,总报错“The process cannot access the file because it is being used fileinfo”,我想实现的是:如果存在,则覆盖,如果不存在,则新建,但是这样根本就不行,那个错时为什么呢?或者应该怎么解决?请求解答~~~非常感谢!
try
{
FileInfo myfile = new FileInfo(path);
if (false == myfile.Exists)
{
StreamWriter sw = myfile.CreateText();
sw.Write(edrtext);
sw.Close();
}
else
{
myfile.Delete();
}
}
因为path这个路径的文件已经存在,所以在myfile.Delete()时,总报错“The process cannot access the file because it is being used fileinfo”,我想实现的是:如果存在,则覆盖,如果不存在,则新建,但是这样根本就不行,那个错时为什么呢?或者应该怎么解决?请求解答~~~非常感谢!
StreamWriter sw = File.CreateText(path);
sw.Write(edrtext);
sw.Close();
streamwriter sw=new streamwriter(fs);
sw.write(.....);
sw.close();
fs.close();
就是这样在CreateText的地方会报那个错。
fileInfo.Delete();文件正由另一进程使用,因此该进程无法访问该文件 public void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password)
{
//1. check target//检查目标
string target;
if (targetDir.Trim() == "")
{
return;
}
target = Guid.NewGuid().ToString();
target = Guid.NewGuid().ToString(); //使用临时文件名
string URI = "FTP://" + hostname + "/" + targetDir + "/" + target;
//WebClient webcl = new WebClient(); System.Net.FtpWebRequest ftp = GetRequest(URI, username, password); //设置FTP命令
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftp.UseBinary = true;
ftp.UsePassive = true; //告诉ftp文件大小
ftp.ContentLength = fileinfo.Length;
const int BufferSize = 2048;
byte[] content = new byte[BufferSize - 1 + 1];
int dataRead; //上传文件内容
using (FileStream fs = fileinfo.OpenRead())
{
try
{
using (Stream rs = ftp.GetRequestStream())
{
do
{
dataRead = fs.Read(content, 0, BufferSize);
rs.Write(content, 0, dataRead);
}
while (!(dataRead < BufferSize));
rs.Close();
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
finally
{
fs.Close();
}
}
ftp = null; //设置FTP命令
ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
ftp.RenameTo = fileinfo.Name;
try
{
ftp.GetResponse();
}
catch (Exception ex)
{
ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
ftp.GetResponse();
throw ex;
}
finally
{
fileinfo.Delete();
} //可以记录一个日志 "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
ftp = null;
//System.Windows.Forms.MessageBox.Show("文件上传成功!");
}