| Start | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Delete a file To delete a file (if you have required permissions) is as simple as: However many things may go wrong:
Note that last point (file does not exist) is usually circumvented with a code snippet like this: However it's not an atomic operation and file may be delete by someone else between the call to Note that this I/O errors sometimes are transitory (file in use, for example) and if a network connection is involved then it may automatically recover without any action from our side. It's then common to retry an I/O operation few times with a small delay between each attempt: Note: in Windows environment file will not be really deleted when you call this function, if someone else open the file using |
||||||||||||||||
| Strip unwanted lines from a text file To change a text file is not easy because its content must be moved around. For small files easiest method is to read its content in memory and then write back modified text. In this example we read all lines from a file and drop all blank lines then we write back to original path: If file is too big to load it in memory and output path is different from input path: |
||||||||||||||||
| Convert text file encoding Text is saved encoded (see also Strings (opens new window) topic) then sometimes you may need to change its encoding, this example assumes (for simplicity) that file is not too big and it can be entirely read in memory: When performing conversions do not forget that file may contain BOM (Byte Order Mark), to better understand how it's managed refer to Encoding.UTF8.GetString doesn't take into account the Preamble/BOM (opens new window). |
||||||||||||||||
| Enumerate files older than a specified amount This snippet is an helper function to enumerate all files older than a specified age, it's useful - for example - when you have to delete old log files or old cached data. Used like this: Few things to note:
|
||||||||||||||||
Move a File from one location to another File.Move
However, there are many things that could go wrong with this simple operation. For instance, what if the user running your program does not have a Drive that is labelled 'C'? What if they did - but they decided to rename it to 'B', or 'M'? What if the Source file (the file in which you would like to move) has been moved without your knowing - or what if it simply doesn't exist. This can be circumvented by first checking to see whether the source file does exist: This will ensure that at that very moment, the file does exist, and can be moved to another location. There may be times where a simple call to A See below for possible exceptions:
|
||||||||||||||||
| "Touch" a large amount of files (to update last write time) This example updates last write time of a huge number of files (using Syntax
Parameters
|
Read Article
https://develop.horje.com/learn/1434/reference