git - How to undo local changes to a specific file

ID : 10228

viewed : 27

Tags : gitgit-revertgit

Top 5 Answer for git - How to undo local changes to a specific file

vote vote


You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.

2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

vote vote


Try this function ...

public static string GetTempFilePathWithExtension(string extension) {   var path = Path.GetTempPath();   var fileName = Guid.NewGuid().ToString() + extension;   return Path.Combine(path, fileName); } 

It will return a full path with the extension of your choice.

Note, it's not guaranteed to produce a unique file name since someone else could have technically already created that file. However the chances of someone guessing the next guid produced by your app and creating it is very very low. It's pretty safe to assume this will be unique.

vote vote


public static string GetTempFileName(string extension) {   int attempt = 0;   while (true)   {     string fileName = Path.GetRandomFileName();     fileName = Path.ChangeExtension(fileName, extension);     fileName = Path.Combine(Path.GetTempPath(), fileName);      try     {       using (new FileStream(fileName, FileMode.CreateNew)) { }       return fileName;     }     catch (IOException ex)     {       if (++attempt == 10)         throw new IOException("No unique temporary file name is available.", ex);     }   } } 

Note: this works like Path.GetTempFileName. An empty file is created to reserve the file name. It makes 10 attempts, in case of collisions generated by Path.GetRandomFileName();

vote vote


You can also alternatively use System.CodeDom.Compiler.TempFileCollection.

string tempDirectory = @"c:\\temp"; TempFileCollection coll = new TempFileCollection(tempDirectory, true); string filename = coll.AddExtension("txt", true); File.WriteAllText(Path.Combine(tempDirectory,filename),"Hello World"); 

Here I used a txt extension but you can specify whatever you want. I also set the keep flag to true so that the temp file is kept around after use. Unfortunately, TempFileCollection creates one random file per extension. If you need more temp files, you can create multiple instances of TempFileCollection.

vote vote


Why not checking if the file exists?

string fileName; do {     fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv"; } while (System.IO.File.Exists(fileName)); 

Top 3 video Explaining git - How to undo local changes to a specific file