0

I need my program to be able to close given files by their names. I played around with processes but came to the realization that I cannot get the process itself properly.

Say I have a "Text.txt" notepad file open I want to close. I tried

   var processesToKill = Process.GetProcessesByName(processName);

   foreach (var process in processesToKill)
   {
       process.Kill();
   }

but came the conclusion that the friendly file name does not help in any way for that so processesToKill is left empty (no such process, duh).

So I get that I have to use, say "notepad" as the processName but I need the program to close different file types/open programs (word, excel, chrome, random .txt or .mp3 files, etc.).

My question is, is there a way to get it to do that without writing massive blocks of code checking under what process the opened file is and close it via CloseMainWindow() or the likes?

Sorry for the rather confusing explanation of the issue, hope I didn't give you too much of a headache/

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 3
    Please see [this](https://stackoverflow.com/questions/317071/how-do-i-find-out-which-process-is-locking-a-file-using-net) question – Guru Stron May 05 '20 at 13:31

1 Answers1

-1

if you use , using statement, it will close the file automatically , after reading. below is just a sample example on how it works.

String path = @"C:\Text.txt";

    using (StreamReader sr = File.OpenText(path))
    {
     String s = "";

     while ((s = sr.ReadLine()) != null)
     {
      Console.WriteLine(s);
     }
awen
  • 79
  • 1
  • 8