0

Hello I'm beginner with C# and I want to delete the last character of my file to inject JSON objects to this file manually (I know that's not the best way to do that), so I can get the right format I tried with multiple ways like open the file, manipulating the string (deleting the last character) and when I try to replace the text in that same file I have errors like IOException: The process cannot access the file 'file path' because it is being used by another process or System.UnauthorizedAccessException : 'Access to the path 'C:\Users\ASUS\Desktop\Root' is denied.

I'll show you the code :

StoreLogs Log = new StoreLogs()
            {
                Id = ID,
                DateTime = dateT,
                TaskName = task,
                SrcAddress = srcPath,
                DstAddress = path,
                FileSize = DirSize(new DirectoryInfo(srcPath)),
                DelayTransfer = ts.Milliseconds,
            };

            // Record JSON data in the variable
            string strResultJson = JsonConvert.SerializeObject(Log);

            // Show the JSON Data
            // Console.WriteLine(strResultJson);

            // Write JSON Data in another file

            string MyJSON = null;
            string strPath = @"C:\Users\ASUS\Desktop\Backup\logs\log.json";



            if (File.Exists(strPath))
            {
                //FileInfo table = new FileInfo(strPath);
                //string strTable = table.OpenText().ReadToEnd();
                //string erase = strTable.Remove(strTable.LastIndexOf(']'));
                //Console.WriteLine(erase);

                //StreamReader r1 = new StreamReader(strPath);
                //string strTable = r1.OpenText().ReadToEnd();
                //string erase = strTable.Remove(strTable.LastIndexOf(']'));
                //r1.Close();

                using (StreamReader sr = File.OpenText(strPath))
                {
                    string table = sr.ReadToEnd();
                    string erase = table.Remove(table.LastIndexOf(']'));
                    sr.Close();
                    File.WriteAllText(strPath, erase);
                }



                //MyJSON = "," + strResultJson;
                //File.AppendAllText(strPath, MyJSON + "]");
                //Console.WriteLine("The file exists.");
            }
            else if (!File.Exists(strPath))
            {
                MyJSON = "[" + strResultJson + "]";
                File.WriteAllText(strPath, MyJSON);
                Console.WriteLine("The file doesn't exists.");
            }
            else
            {
                Console.WriteLine("Error");
            }


            // End
            Console.WriteLine("JSON Object generated !");


            Console.ReadLine();

And that's the result I want : [{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0},{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0},{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0}]

Edit : Thank you all for your advices

Solution:

FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.ReadWrite);
            fs.SetLength(fs.Length - 1);
            fs.Close();
therealwalim
  • 252
  • 1
  • 4
  • 18
  • do you mean to be opening srcPath and not strPath? – Garr Godfrey Nov 26 '19 at 18:11
  • So the message is accurate: Either the file is left open before writing, or you don't have write permissions to write to it. I would eliminate one possibility and that is to first put the .json file in your executing folder, just to eliminate the permission issue. Two, I would write to a new file, then after that is successful, delete the original, and rename the new file to the final name. That way if there's an error in writing the file, you won't accidentally truncate it. – LarryBud Nov 26 '19 at 18:15
  • I got another error ```System.ArgumentOutOfRangeException : 'StartIndex cannot be less than zero. ``` – therealwalim Nov 26 '19 at 18:19

3 Answers3

4

In the code example you have posted you are opening a stream to read the file. A using block will dispose the stream after you exit the block. You are trying to write to the file, while the read stream is still accessing it (the read stream still exists). You've basically opened the file, you read from it, and are trying to write back to it while still holding it open. The reason this is a problem is that you are not using the stream to write. So your second, write, process is unable to access the file. I see you are closing the stream prior to write, but I'm willing to bet it's still holding the reference open.

I would try this method: How to both read and write a file in C#

mminneman
  • 426
  • 3
  • 7
1

what it says is the access to the path (C:\Users\ASUS\Desktop\Root) denied for the user who is running the application. for ex: If you are running from Visual studio on user1 windows login then user1 should have appropriate rights to that root folder. If the code is running by itself (exe) then check the access for that user who is invoking that exe.

The bug
  • 46
  • 4
  • I don't think so because there's only one user in my computer and I checked the rights – therealwalim Nov 26 '19 at 18:21
  • your code is working on my machine without any issues. if you dont have that character in file ']' then it throws error as System.ArgumentOutOfRangeException. – The bug Nov 26 '19 at 18:42
1

Based on the errors you posted seems that:

  1. Maybe you're leaving some stream open pointing to the file you want to edit, use the 'using' statement to avoid this (see this link for more info)

  2. You're trying to access a file when you don't have needed permissions (you aren't a system admin or file is read-only), try changing file ubication or setting it to be writeable (see this link for mor info about the UnauthorizedAccessException exception)

Hope this helps you!

Jorge C.M
  • 375
  • 3
  • 11