首页 > 解决方案 > 如何用C#删除文件的最后一个字符

问题描述

您好,我是 C# 的初学者,我想删除文件的最后一个字符以手动将 JSON 对象注入该文件(我知道这不是最好的方法),所以我可以得到正确的格式,我尝试了多个打开文件、操作字符串(删除最后一个字符)以及尝试替换同一个文件中的文本时出现类似IOException: The process cannot access the file 'file path' because it is being used by another processSystem.UnauthorizedAccessException : 'Access to the path 'C:\Users\ASUS\Desktop\Root' is denied.

我将向您展示代码:

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();

这就是我想要的结果: [{"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}]

编辑: 谢谢大家的建议

解决方案:

FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.ReadWrite);
            fs.SetLength(fs.Length - 1);
            fs.Close();

标签: c#jsonsubstringdata-manipulationstreamwriter

解决方案


在您发布的代码示例中,您正在打开一个流来读取文件。using 块将在您退出块后处理流。您正在尝试写入文件,而读取流仍在访问它(读取流仍然存在)。您基本上已经打开了该文件,您从中读取,并试图写回它,同时仍然保持打开状态。这是一个问题的原因是您没有使用流进行写入。因此,您的第二个写入进程无法访问该文件。我看到您在写入之前关闭了流,但我敢打赌它仍然保持引用打开。

我会尝试这种方法: 如何在 C# 中读取和写入文件


推荐阅读