.Net 中的临时文件
我需要创建一些位图并将它们保存到文件系统中。由于某种原因,MScharting 系统希望其后台文件以字符串形式的路径提供。
我正在动态创建背景图像,尽管只有几次。
创建这些文件然后清理它们的最佳方法是什么?
I need to create some bitmaps and save them to the file system. For some reason the MScharting system wants it's background files supplies as paths in string form.
I'm dynamically creating the background image, although only a few times.
What's the best way to create these files and then clean them up?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下是获取临时文件的完整路径和文件名的方法:
使用此文件名创建文件并创建临时文件。路径,完成后将其删除。
Here's how you can get the full path and file name of a temporary file:
Create the file using this filename & path and when you're done delete it.
最好的选择是拥有一个实现 IDisposable 的 TemporaryFileManager;你要求它提供临时文件,它会自动生成并粘贴在某个临时目录中,然后当 TemporaryFileManager 被你或终结器释放时,它们都会被删除(如果你已经正确实现了一次性模式)
Your best bet is to have a TemporaryFileManager that implements IDisposable; you ask it for temporary files, which it auto-generates and sticks in a temp directory somewhere, then they all get deleted when the TemporaryFileManager gets disposed, either by you or the finalizer (if you've implemented the disposable pattern correctly)
在我的项目中,我有一个名为 TempFile 的辅助类。它有几个静态方法,我用它们将流(或字节数组,如果需要)写入临时文件。这是此类方法的一个简化示例:
然后,我有另一个方法接受文件路径以供稍后删除,该方法是我的“解析”类的成员,尽管您可以将其放入其自己的静态帮助器类中:
最后,我这样做以下
是我想出的解决 API 缺乏流处理功能的最佳方法。
In my projects, I have a helper class called TempFile. It has several static methods that I use to write a stream (or an array of bytes if need be) to a temporary file. Here's a simplified example of such a method:
Then, I have another method that accepts a file path for later deletion which is a member of my 'parsing' class, although you could put it in its own static helper class:
Finally, I do the following:
This is the best way I've come up with for circumventing an API's lack of stream handling capabilities.
我使用这个解决方案:
每次需要临时文件时,请使用:
为了确保在应用程序关闭或崩溃后将所有临时文件删除,放在
应用程序启动时。
I use this solution:
Every time you need temporary file use:
To be sure all temporary files are deleted after application closes or crashes put
at start of the application.