Close a File in Managed
In the std:: you can close an open file like this:
But if you have opened a File in Managed, how do you close a file here:
System::IO::File::Open // Here I canīt find Close as a member to File::
The Open method of File returns a FileStream. This object has a Close method.
Normally, the File class is used for everything that does not concern the contents of a file. Moving, Deleting, Renaming, Copying, Check, Encrypt/Decrypt. Whenever you want to do something that's more complex than reading the whole file to RAM or writing a block of RAM to file, you will need StreamReader or StreamWriter (or derived) classes. You can look them up on MSDN.
Ok, thanks alot for the information, I will check this up.
Though I might wonder, I have managed to write a code that works in that way, that if the (Source) file have made a change, this file will be copied/replace the (Dest) file.
What I wonder with this code is that if any of the files (Source) or (Dest) is opened or lefter opened or is the two files under and after the whole process closed ?
What I then might wonder is that to make this process work, I am using an eternity-loop that checks the file all the time.
The problem though is that the processor peeks on 100 % all the time.
Is there any other way/approach to make it check this code all the time to avoid this heavy processor work ?
String^ Source = textBox2->Text;
String^ Dest = textBox3->Text;
int i = 4;
while(i > 0)
i = (i + 1);
System::DateTime CurrentWriteTime = System::IO::File::GetLastWriteTime(Source);
System::DateTime LastWriteTime2 = System::IO::File::GetLastWriteTime(Dest);
if( CurrentWriteTime != LastWriteTime && CurrentWriteTime != LastWriteTime2 && System::IO::File::Exists(Dest))
System::IO::File::Copy(Source, Dest, true);
System::DateTime LastWriteTime = System::IO::File::GetLastWriteTime(Source);
if( i > 10000 )
i = 4;
If you use any of System.IO.File's ReadAllBytes/ReadAllText/ReadAllLines/etc... methods the file will be closed automatically.
Yes, you are right. I tried to replace the //code with the these 2 lines. But when the loop is going and I will open the Source file to write something and save it. I will have an errormessage that says:
"The Process cannot access the file (Source) because it is being used by another process."
With the ::Copy method that I have // it do works if I do this.
However the idea of the file to close automatically, I find interesting.. Though I am not sure if the file always remains closed if the file
is copied with the approach I have in the code below after //, If it is, the Copy method should be okay to use in that case I beleive ?
SourceText = System::IO::File::ReadAllText(Source);
//System::IO::File::Copy(Source, Dest, true);