我试图从specipic位置删除excel文件.但不能删除.有错误:
访问路径'C:\ mypath\sample.xlsx'被拒绝.
我写了一个代码:
protected void imgbtnImport_Click(object sender, ImageClickEventArgs e)
{
try
{
string strApplicationPath = HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath);
string strXLStoredDirectoryPath = strApplicationPath + "/Information Documents/";
DirectoryInfo di = new DirectoryInfo(strXLStoredDirectoryPath);
string fileName = flUpldSelectFile.FileName;
if (!File.Exists(strXLStoredDirectoryPath))
{
Directory.CreateDirectory(strXLStoredDirectoryPath);
di.Attributes = FileAttributes.Normal;
}
string strCreateXLFileDestinationPath = strXLStoredDirectoryPath + fileName;
if (File.Exists(strCreateXLFileDestinationPath))
{
File.Delete(strCreateXLFileDestinationPath);
}
flUpldSelectFile.SaveAs(strCreateXLFileDestinationPath);
di.Attributes = FileAttributes.ReadOnly;
}
catch (Exception)
{
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
请指导.........
- *****************************************那里还有问题.它没有解决.获取UnauthorizedAccessException.因访问被拒绝删除文件.我现在累了.请帮忙; 我尝试了很多东西..请帮忙 - *******************************************************************VSS可能是否有效?我正在使用它
use*_*uld 11
部分问题可能是保存/创建此文件.如果您使用内置的"保存"或"另存为"功能,则基础文件流可能仍会锁定文件.使用FileStream包装在Using语句中编写自己的保存逻辑将有助于在完成后立即处理流,从而允许您在相同的上下文中进一步操作文件.
if flUpldSelectFile.SaveAs(strCreateXLFileDestinationPath);是保存文件的唯一逻辑,然后摆脱内置SaveAs功能.使用FileStream包装在Using块中编写自己的保存逻辑.
在您的示例中,我无法看到flUpldSelectFile是什么,所以我假设它是一个System.Web.UI.WebControls.FileUpload控件.以下是滚动自己的保存逻辑的示例.
using (FileStream fs = new FileStream(strCreateXLFileDestinationPath, FileMode.Create))
{
byte[] buffer = flUpldSelectFile.FileBytes;
fs.Write(buffer, 0, buffer.Length);
}
Run Code Online (Sandbox Code Playgroud)
如前所述,使用此工具可以确定另一个进程是否存在对文件的锁定.
弹出这个奇妙的工具并搜索该文件,看看它/锁定了什么
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx 替代文字http://i.technet.microsoft.com/bb896653.ProcessExplorer(en-us,MSDN.10).jpg
| 归档时间: |
|
| 查看次数: |
3364 次 |
| 最近记录: |