【问题标题】:How can I get File.Delete() to actually delete my file?如何让 File.Delete() 实际删除我的文件?
【发布时间】:2015-10-19 16:08:02
【问题描述】:

我生成一个PDF文件,保存在服务器上:

var bytes = ms.ToArray();
. . .
String fileFullpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), pdfFileName);
. . .
File.WriteAllBytes(fileFullpath, bytes);

...然后将其保存到 Sharepoint 文档库中,并将其作为电子邮件附件发送给生成文件的人:

SavePDFToDocumentLibrary(fileFullpath);
String from = GetFromEmailID();
String to = GetUserEmail();
String subjLine = String.Format("The PDF file you generated ({0})", pdfFileName);
String body = String.Format("The Direct Pay PDF file you generated ({0}) is attached.", pdfFileName);
SendEmailWithAttachment(fileFullpath, from, to, subjLine, body);
// Now that it has been put in a Document Library and emailed, delete the file that was saved locally
File.Delete(fileFullpath);

...此时,我不再需要我保存到服务器磁盘上的文件,因此,如上面最后一行所示,尝试删除它。

但是,它不起作用。现在冗余的文件仍在保存位置。

为什么,我怎样才能让它理解“删除”真的意味着“删除”?

更新

以下是 Scott 希望看到的方法:

// This works; got it from Henry Zucchini's answer at http://stackoverflow.com/questions/468469/how-do-you-upload-a-file-to-a-document-library-in-sharepoint
private void SavePDFToDocumentLibrary(String fullpath)
{
    String fileToUpload = fullpath;
    String sharePointSite = siteUrl;
    String documentLibraryName = "DirectPayPDFForms";

    using (SPSite oSite = new SPSite(sharePointSite))
    {
        using (SPWeb oWeb = oSite.OpenWeb())
        {
            if (!System.IO.File.Exists(fileToUpload))
                throw new FileNotFoundException("File not found.", fileToUpload);

            SPFolder doclib = oWeb.Folders[documentLibraryName];

            // Prepare to upload
            Boolean replaceExistingFiles = true;
            String fileName = System.IO.Path.GetFileName(fileToUpload);
            FileStream fileStream = File.OpenRead(fileToUpload);

            // Upload document
            SPFile spfile = doclib.Files.Add(fileName, fileStream, replaceExistingFiles);

            // Commit 
            doclib.Update();
        }
    }
}

// This is adapted from https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage(v=vs.90).aspx
public static void SendEmailWithAttachment(string fileToMail, String from, String to, String subj, String body)
{
    String server = GetSMTPHostName(); //"468802-DEV-SPWF"; // change this to prod when go live, or programatically assign?
    // Specify the file to be attached and sent. 
    string file = fileToMail;
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage(
       from,
       to,
       subj,
       body);

    // Create  the file attachment for this e-mail message.
    Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
    // Add time stamp information for the file.
    ContentDisposition disposition = data.ContentDisposition;
    disposition.CreationDate = System.IO.File.GetCreationTime(file);
    disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
    disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
    // Add the file attachment to this e-mail message.
    message.Attachments.Add(data);

    //Send the message.
    SmtpClient client = new SmtpClient(server);
    // Add credentials if the SMTP server requires them.
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", ex.ToString());
    }
    // Display the values in the ContentDisposition for the attachment.
    // May not need/want this section
    ContentDisposition cd = data.ContentDisposition;
    Console.WriteLine("Content disposition");
    Console.WriteLine(cd.ToString());
    Console.WriteLine("File {0}", cd.FileName);
    Console.WriteLine("Size {0}", cd.Size);
    Console.WriteLine("Creation {0}", cd.CreationDate);
    Console.WriteLine("Modification {0}", cd.ModificationDate);
    Console.WriteLine("Read {0}", cd.ReadDate);
    Console.WriteLine("Inline {0}", cd.Inline);
    Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
    foreach (DictionaryEntry d in cd.Parameters)
    {
        Console.WriteLine("{0} = {1}", d.Key, d.Value);
    }
    // </ May not need/want this section
    data.Dispose();
}

更新 2

我在单步执行时看到,添加此测试后:

if (File.Exists(fileFullpath))
{
    File.Delete(fileFullpath);
}

...毕竟在 IOException 捕获块中有 一个异常:

进程无法访问文件“C:\Users\TEMP.SP.018\Desktop\DirectPayDynamic_2015Jul28_19_02_clayshan_0.pdf”,因为它正被另一个进程使用。

那么其他方法之一是如何坚持下去的呢? ISTM 认为 SavePDFToDocumentLibrary() 是安全的,因为它使用 using 块。

是 data.Dispose();在 SendEmailWithAttachment() 中还不够吗?我需要在那里显式调用 close 吗?

更新 3

我添加了“message.Dispose();”就在“data.Dispose();”之前在 SendEmailWithAttachment() 中,但没有区别。

【问题讨论】:

  • 您在SavePDFToDocumentLibrarySendEmailWithAttachment 中有一个错误,它没有关闭文件。您需要显示这两种方法的代码。特别是您使用fileFullpath 打开文件的位置
  • 根据documentation,如果文件不存在,它不会抛出异常。在文件被删除之前进行 File.Exists() 检查,看看它是否因任何奇怪的原因不存在。
  • 您可能还想处理SmtpClientMailMessage(通过using 语句隐式处理)
  • 我以前也遇到过这种情况,不得不求助于重试/休眠方案——不知何故,文件系统没有立即释放锁。如果您不想正确对待它们,您可以在特定文件夹中创建文件并删除该文件夹中超过一分钟的所有文件......当您的代码按原样进行时,这两者都是丑陋的黑客工作。
  • @B.ClayShannon using File.OpenRead in SavePDFToDocumentLibrary 怎么样?

标签: c# file sharepoint-2010 delete-file


【解决方案1】:

尝试像这样处理SavePDFToDocumentLibrary中使用的文件流:

using (FileStream fileStream = File.OpenRead(fileToUpload))
{
    ...
}

【讨论】:

    猜你喜欢
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多