Click here to Skip to main content
16,008,490 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Ia developing a windows application. In this for sorting. first I am reading all the lines of file and at the last writing all lines to that file but it is giving me error"this pocess can not access the file because its is used by another process"
Please help me I am new to c#. trying to learn.

C#
try
{
string[] input_lines = File.ReadAllLines("C:\\maq\\" + main1.text + "\\" + main1.text + ".txt");
              List<string>  input_lines_list  = input_lines.ToList();
                input_lines_list.RemoveAt(0);
                input_lines_list = input_lines_list.OrderBy((s) => s.Split(',')[0]).ThenByDescending((s) => DateTime.ParseExact(s.Split(',')[1], "yyyyMMdd", null)).ToList();
                int j = 0;
                while (j < input_lines_list.Count - 1)
                {
                    string[] line_detail = input_lines_list[j].Split(',');
                    string[] next_line_detail = input_lines_list[j + 1].Split(',');
                    if (line_detail[2] == line_detail[3] && line_detail[3] == line_detail[4] && line_detail[4] == line_detail[5] && line_detail[5] == input_lines_list[j + 1].Split(',')[5])
                    {
                        input_lines_list.RemoveAt(j);
                        continue;
                    }
                    else if (line_detail[0] == next_line_detail[0] && line_detail[2] == next_line_detail[2] && line_detail[3] == next_line_detail[3] && line_detail[4] == next_line_detail[4] && line_detail[5] == next_line_detail[5])
                    {
                        input_lines_list.RemoveAt(j + 1);
                        continue;
                    }
                    else if (line_detail[0] == next_line_detail[0] && line_detail[1] == next_line_detail[1])
                    {
                        input_lines_list.RemoveAt(j + 1);
                        continue;
                    }
                    j += 1;
                }
          }
          catch(Exception ex)
          {
                  MessageBox.Show(ex.Message);
          }

                input_lines_list.Insert(0, iplut_lines[0])

            File.WriteAllText("C:\\maq\\" + main1.text + "\\" + main1.text + ".txt", "\n");
            System.IO.File.WriteAllLines("C:\\maq\\" + main1.text + "\\" + main1.text + ".txt", input_lines_list);
 }
Posted

1 solution

You cannot just close it. You need to find out the root of the problem and sort it out. For further detail and some practical recommendations, please see my past answer: File used by another process exception[^].

—SA
 
Share this answer
 
v2

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