1

I am trying to read from a folder, and delete a specified file from inside. I am able to do this one time without any issues. However after doing it the first time, I am no longer able to Create the new file. The old one is still deleted, but the new file is no longer being created as it should. My question is; From the code provided why would the task work once, but not after that? It's being deleted after the first time but won't re-create.

EDIT: The issue was in permissions. I changed the folder security settings to allow reading/writing and I am now able to do it as I wanted. However, I need it to automatically set the security settings if possible as other users may not know how to do so.

if (Directory.Exists(path1))
{
    if (File.Exists(path1 + "\\launchinfo.txt"))
    {
        File.Delete(path1 + "\\launchinfo.txt");
        using (FileStream fs = File.Create(path1 + "\\launchinfo.txt"))
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("[Connection]\n" + Form1.ipaddress + "\nport=0000\nclient_port=0\n[Details]\n" + Form1.playername);
            fs.Write(info, 0, info.Length);
        }
    }
    else
    {
        using (FileStream fs = File.Create(path1 + "\\launchinfo.txt"))
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("[Connection]\n" + Form1.ipaddress + "\nport=0000\nclient_port=0\n[Details]\n" + Form1.playername);
            fs.Write(info, 0, info.Length);
        }
    }
}
Lynnstrum
  • 194
  • 1
  • 3
  • 17
  • 3
    Please always use Path.Combine. Never try to concat paths. – Benjamin Abt Sep 15 '16 at 12:32
  • Possible duplicate of [Why isn't there an asynchronous file delete in .net?](http://stackoverflow.com/questions/10606328/why-isnt-there-an-asynchronous-file-delete-in-net) – Lajos Arpad Sep 15 '16 at 12:40
  • `File.Delete()` calls the Windows API [`DeleteFile()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363915(v=vs.85).aspx) function. It is a blocking call. – Matthew Watson Sep 15 '16 at 12:46
  • @MatthewWatson Wouldn't that prevent it from deleting the file at all though? It deletes it just fine. It just won't re-create it. – Lynnstrum Sep 15 '16 at 12:50
  • @Lynnstrum Sorry, My comment was in response to juharr, it isn't really relevant to your issue. – Matthew Watson Sep 15 '16 at 12:51
  • This code should work; if it doesn't, it must be because of some other factor. Try running it under the debugger and see if anything shows up. – Matthew Watson Sep 15 '16 at 12:52
  • what is youre error ? – lordkain Sep 15 '16 at 12:54
  • I am not getting any errors, it's just not creating the new .txt file. – Lynnstrum Sep 15 '16 at 13:18
  • Do you have a try/catch block around this code? If so, please post it. – Lasse V. Karlsen Sep 15 '16 at 13:36
  • if youre not getting any errors, are you certain that the file isn't being created again? – Simon Price Sep 15 '16 at 13:40
  • also, what happens when you step through using the debugger? – Simon Price Sep 15 '16 at 13:41
  • @SimonPrice After changing permissions of the folder I am able to write to it over and over. However now my issue is setting permissions to folder(To write new file) through code, and not have to do it manually. – Lynnstrum Sep 15 '16 at 13:43
  • that's pretty simple to complete and a good example can be found here https://msdn.microsoft.com/en-us/library/system.io.directory.setaccesscontrol(v=vs.110).aspx – Simon Price Sep 15 '16 at 13:44
  • @SimonPrice That lists @"MYDOMAIN\MyAccount however is there a way to get that from the script? Otherwise everyone will have to have the same domain and account as me... – Lynnstrum Sep 15 '16 at 13:56
  • rather than using MYDOMAIN\MyAccount substitute MyAccount for a security group – Simon Price Sep 15 '16 at 14:08

1 Answers1

2

You've not posted any possible exception you may be running into - if you do have one, please post it.

That being said, it's possible that you're encountering File in use by another process when trying to delete the file - especially if you're calling your function moments after creating a file.

A method to get around this is to check if a process is using the file before you try to delete it.

string fullPath = Path.Combine(path1, "launchinfo.txt");
if (Directory.Exists(path1))
 {
      if (File.Exists(fullPath))
      {  
         // Call a method to check if the file is in use.         
         if (IsFileLocked(new FileInfo(fullPath)){
            // do something else because you can't delete the file
         } else {
             File.Delete(fullPath);
          }
      }

      using (FileStream fs = File.Create(fullPath))
      {
         Byte[] info = new UTF8Encoding(true).GetBytes("[Connection]\n" + Form1.ipaddress + "\nport=0000\nclient_port=0\n[Details]\n" + Form1.playername);
         fs.Write(info, 0, info.Length);
       }
 }

A method to check if the file is in use by another process

 protected virtual bool IsFileLocked(FileInfo file)
    {
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
        }
        catch (IOException)
        {
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }    
        //file is not locked
        return false;
    }
Darren Wainwright
  • 30,247
  • 21
  • 76
  • 127
  • This didn't work either. I didn't get any exceptions for the file being locked. New .txt is still not being created inside the directory. – Lynnstrum Sep 15 '16 at 13:17
  • Have you stepped through it with the debugger? There is so much more information you can garnish which would help us identify the problem - what about your connection to fetch the file? Is this failing? – Darren Wainwright Sep 15 '16 at 13:43
  • @Darren53 I got it to work after changing file permissions, however how do I do that with c# to automatically allow me to write a new file to the path. – Lynnstrum Sep 15 '16 at 13:45
  • changing what file permissions?? – Darren Wainwright Sep 15 '16 at 13:46
  • Changed the file permission of the directory. path1 – Lynnstrum Sep 15 '16 at 13:56
  • Is your code creating the directory? There is so much more you should really be showing/asking - however, if you are creating the directory then you can set the permissions with Directory.SetAccessControl https://msdn.microsoft.com/en-us/library/system.io.directory.setaccesscontrol(v=vs.110).aspx – Darren Wainwright Sep 15 '16 at 14:02
  • The directory is pre-existing. All I'm creating is the new file. – Lynnstrum Sep 15 '16 at 14:09
  • you need to ask a new question. – Darren Wainwright Sep 15 '16 at 14:13