Click here to Skip to main content
15,667,422 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
hello, my code is working only for one file, but i have multiple json files and i have to remove last comma from each json files.

What I have tried:

string filepath = "E:/prod/1.json";
            string result = string.Empty;
            using (StreamReader r = new StreamReader(filepath))
                var json = r.ReadToEnd();
                var test = json;
                var lastComma = test.LastIndexOf(',');
                foreach (var item in test)
                    if (lastComma != -1) result = test.Remove(lastComma, 1);
            File.WriteAllText(filepath, result);
Updated 26-Oct-21 11:32am
OriginalGriff 26-Oct-21 5:28am    
What does it do that you didn't expect, or not do that you did?
What have you tried to do to find out why?
Are there any error messages, and if so, where and when? What did you do to make them happen?

This is not a good question - we cannot work out from that little what you are trying to do.
Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with.
Use the "Improve question" widget to edit your question and provide better information.
PIEBALDconsult 26-Oct-21 9:58am    
If they are well-formed, then won't removing the commas break them?
If they are not well-formed, then throw them back and require the sender to fix them. Fixing them is not your job.
Member 15329613 26-Oct-21 10:50am    
Maybe that's exactly his job. ;)
PIEBALDconsult 26-Oct-21 10:58am    
More likely a class exercise.

1 solution

So you have some code which does the job for one file.
You could:
- take the part which is reponsible for processing one file, and make it a method. Give this method the path to the file to be processed as a parameter.
- then enumerate the files to be processed, calling the method for each of them.
using System.IO;

void ProcessOneFile(string path)
   // process the file having 'path' here

// Somewhere else in your code

DirectoryInfo folder = new DirectoryInfo(/* path to folder */);
foreach (FileInfo file in di.EnumerateFiles("*.json"))
   ProcessOneFile(Path.Combine(folder.FullName, file.Name));

[Edit] Related links which may be useful:
DirectoryInfo Class (System.IO) | Microsoft Docs[^]
FileInfo Class (System.IO) | Microsoft Docs[^]
File Class (System.IO) | Microsoft Docs[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900