文件打开和关闭检查 [英] File Open and Close Checking

查看:59
本文介绍了文件打开和关闭检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何为
编写一个方法
如果打开了给定的文件,则关闭文件,反之亦然?

How can i write a single method for

if a given file is opened then close and vice versa?

推荐答案

使用using块来确保每次打开文件时都关闭每个n.喜欢...

use using block to make sure each n every time file is closed when you open it.... like...

using (StreamWriter sw = new StreamWriter(fullFilePath, true))
{
     sw.WriteLine(string.Format("String that you want to append"));
}


您还可以使用lock关键字锁定其他对象.....


you can also lock the other object with the use of lock keyword.....


转到此链接
http://stackoverflow.com/questions/1304/how-to- check-for-file-lock-in-c [ ^ ]
http://www.eggheadcafe .com/community/aspnet/2/28946/how-to-know-if-th-file-is-open-.aspx [ http://bytes.com/topic/c- sharp/answers/261124-check-if-file-allready-open-other-application [
go this link
http://stackoverflow.com/questions/1304/how-to-check-for-file-lock-in-c[^]
http://www.eggheadcafe.com/community/aspnet/2/28946/how-to-know-if-th-file-is-open-.aspx[^]
http://bytes.com/topic/c-sharp/answers/261124-check-if-file-allready-open-other-application[^]


我仍然不知道详细信息,但我敢肯定,使用状态未知的文件对象的整个想法是对技术的巨大滥用.
.

正确的主意是:文件/流变量从文件第一次打开的那一点开始就永远不会在堆栈外部可见.它永远不能是静态变量,甚至不能是类字段. 您需要使用一种方法打开和关闭文件.您应该使用Parmar答案中显示的模式.

实际上,您可以将文件/流变量传递给其他方法,但只能将其作为参数(因为对同一流的写/读操作可能非常复杂,并且需要一些抽象工具),因此,我在前几段中阐述的原理将不被违反.

如果您想违反这些原则,请准备一些麻烦.最好不要这样做!

—SA
I still don''t know the details, but I''m sure the whole idea of working with the file object with unknown status it a huge abuse of the technology.

The right idea would be: a file/stream variable should never be visible outside the stack starting from the point the file is first open. It should never be a static variable or even a class field. You need to open and close the file in one single method. You should use the pattern shown in the answer by Parmar.

You can actually pass the file/stream variable to other methods but only as a parameter (because write/read operations on the same stream could be quite complex and need some abstraction tools), in this way the principles I formulated in the previous paragraphs would not be violated.

If you want to violate these principles, get ready to some trouble. Better don''t do it!

—SA


这篇关于文件打开和关闭检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆