C#: What are some things i need to know about opening and saving files (eg. validation)
i am using the common file dialog. i think there will be many things i need to know and validate eg. file type, file exists, not enough memory etc.
for file type, can i limit file types that can be opened using open file dialog? filter seems to still allow the user to type in a file with a different filetype. must开发者_Python百科 i validate in code?
can i say that just by setting CheckFileExists = True
, i should not need to check again in code the file exists?
is there a need to validate if there is a OutOfMemoryException
? i am thinking, if all i should be opening is small files, i can get away with not handling that? not a good practice i guess?
are there any others i missed out?
Yes, you need to validate that a file selected with OpenFileDialog
exists and is of correct type as these cannot be enforced. As far as OutOfMemoryException
is concerned I am afraid there's no reliable way to test if it will occur. Even if you try to see available memory and verify that this number is greater than the file size an exception could still occur later when you try to read the file because the garbage collector or some other process might have changed this.
Checking for every possible scenario is not very good strategy. A file that exists on line 39 could easily be gone by line 45. Large object heap fragmentation is also something that is quite hard to spot and a very common reason to get a OOM exception. IMHO you should just try to do whatever you want with the file and handle the exceptions thrown by the IO layer.
You can check the file type if that is important and also if the file exists.
bool fileExists = File.Exists("file.txt")
You should open the file for reading or writing inside "using" block to ensure the file handle is released correctly.
using (StreamReader reader = new StreamReader("file.txt"))
{
string line = reader.ReadLine();
}
There are many exceptions that can be thrown when writing to disk so you should handle them. If you do your file access inside a try-catch block you can catch any exception that occurs and handle it.
try
{
// work with file
}
catch(Exception e)
{
// handle any exception
}
精彩评论