Click here to Skip to main content
15,886,016 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to copy data of one file and pasting it into the same file which means overwriting it. I learn that overwrite the file data using file.copy() cannot be possible. but from the one of the post says that if I use File.Copy(Source file, destination file, true) than overwrite is possible. I tried to use but it didn't work. if anyone have solution for that than it will be big help.


What I have tried:

  public void EditRole(string oldRole, string newRole)
        {
          if (File.Exists(roleXMLLoc))
            {
                XDocument doc = XDocument.Load(roleXMLLoc);
                var edit = doc.Element("Roles").Elements("Role").Where(x => x.Value == oldRole).SingleOrDefault();
                edit.Value = newRole;
                doc.Save(roleXMLLoc);

                if (File.Exists(userPermissionLoc))
                {
                  File.Copy(userPermissionLoc, userPermissionLoc, true); SaveData();
                }
          }
}
Posted
Updated 4-Mar-21 22:00pm

1 solution

No, you can't copy a file onto itself: what would be the point? The boolean parameter just allows you to overwrite existing files, not to overwrite a file with itself.

Even if you could, the first act of copying the file would be to delete the existing output file, so the source file would no longer exist in order to be copied. Since the system doesn't read the whole file into memory before writing it to the output - that would be monumentally inefficient - all you could end up with is an empty file.

Even if that worked, all you would get is the same file you started with: nothing changed at all which would make it a very pointless procedure.

What are you trying to do that you think you need this?
 
Share this answer
 
Comments
Member 15073686 5-Mar-21 4:12am    
I am making a WPF application to create user access management and it has check box to the permissions. The thing is whenever I edit or change the users name than all the permissions will set to False or all the checkbox will be unchecked. my requirements are whenever I edit the name of the user the checkbox stay checked. I am fetching data from XML file.
OriginalGriff 5-Mar-21 4:31am    
What on earth does that have to do with copying files?
Member 15073686 5-Mar-21 4:36am    
than what else can I do. I am open for suggestions.
OriginalGriff 5-Mar-21 5:05am    
I have no idea what you are trying to do that you think it would help with: try to explain in terms that someone who can't see your screen - and isn't going to try wading through your whole app to get an idea - can understand.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900