There is a configuration file in a small program I wrote recently. This file is crucial to the entire program. If it is deleted or rewritten, the entire program cannot run or cannot be closed after running. So I've been looking for a way to make it impossible to rewrite files manually.
"Delete" is easy to solve. Find the path of the configuration file in the program, create it if it is empty, and give some default values. The sample code of VB is as follows:
FileName = App.Path + "/CONFIG"'If the file does not exist, create the fileIf Dir(FileName) = "" Then Open FileName For Output As #1 'To open a sequential file, we can use the Open statement a = Encode(" 123") + vbCrLf + "10" + vbCrLf 'vbCrLf is carriage return Print #1, a 'Write dataClose #1 'Close the fileEnd If
I have been unable to manually rewrite the configuration file. I tried to hide the file in the program. The sample code of VB is as follows:
SetAttr FileName, vbSystem Or vbHidden 'Hidden file
But in the final analysis, it is treating the symptoms rather than the root cause, and the document will still be rewritten. Then I thought of modifying the configuration file suffix method so that it would not be easy for people to open the file manually, but there is always a way to open it. In the end, I thought of a simple solution: open the configuration file in the program first, and then it cannot be opened manually. The sample code of VB is as follows:
Open FileName For Binary As #99
Just remember that the program must first close the open file when rewriting the file, otherwise the rewriting will fail. The sample code of VB is as follows:
Close #99 'Close the file
To sum up, the simple way to prevent a file from being overwritten is to open the file first in the program.
The above is the entire content of this article, I hope you all like it.