процесс c # не может получить доступ к файлу, потому что он используется другим процессом

Я написал этот код.

        string filepath = (string)command.ExecuteScalar();
        string gfile = Server.MapPath("//" + filepath);

        connection.Close();


        string path = newFile(aid);


        string AttributeDeclaration = "@ATTRIBUTE";
        string AttributeDeclaration2 = "@attribute";
        string Relation = "@RELATION";
        string Relation2 = "@relation";
        string Data = "@DATA";
        string Data2 = "@data";


        string line;


        using (FileStream fsReader = new FileStream(gfile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            using (StreamReader sr = new StreamReader(fsReader))
            {
                while ((line = sr.ReadLine()) != null)
                {


                    if (line.StartsWith(Relation) | line.StartsWith(Relation2))
                    {

                        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            fs.Close();
                        }
                        try
                        {
                            using (StreamWriter writer = new StreamWriter(path, true))
                            {
                                writer.WriteLine(line);
                                writer.Flush();
                                writer.Close();
                                writer.Dispose();
                            }
                        }
                        catch (IOException)     
                        {

                        }



                    else if (line.StartsWith(AttributeDeclaration) | line.StartsWith(AttributeDeclaration2))
                    {

                        var data = line.Split(new Char[] { ' ', '\t' }, 3);
                        string attri = (data[0]);
                        string name = (data[1]);
                        string type = (data[2]);
                        Save(aid, attri, name, type);
                    }


                }

                sr.Close();
            }

        }
}
    }




 private string newFile(int aid)
    {
        string folderName = @"C:\Users\valentina\Downloads\Desktop\web respository"; //@"C:\Users\valentina\Documents\Visual Studio 2010\Projects\WebRepository3\WebRepository3\files";
        string pathString = System.IO.Path.Combine(folderName, "CreateFiles");
        string fileName = System.IO.Path.GetRandomFileName();

        pathString = System.IO.Path.Combine(pathString, fileName);
        string newfilePath = System.IO.Path.ChangeExtension(pathString, ".txt");
        System.IO.File.Create(newfilePath);


        SqlConnection con = new SqlConnection("Data Source=VALENTINA-PC\\SQLEXPRESS;Initial Catalog=repository_db;Integrated Security=True");
        SqlCommand command = con.CreateCommand();


        command.CommandText =
        @"INSERT INTO new_file
        (set_id, path) 
      VALUES 
        (@set_id, @path)";

        con.Open();


        command.Parameters.Add("@set_id", SqlDbType.Int).Value = aid;
        command.Parameters.Add("@path", SqlDbType.NVarChar, 1000).Value = newfilePath;

        command.ExecuteNonQuery();

        con.Close();
        return (newfilePath);
    }

Но у меня есть ошибка, и процесс не может получить доступ к файлу, потому что он используется другим процессом. Ошибка заключается в использовании (FileStream fs = new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) .. Если я удалю его, строка ошибки будет ниже StreamWriter. Я пробовал все, с ReadAllLInes, без Close ... Кто-нибудь может помочь мне решить эту проблему.

Код должен делать то, что он читает из txt, файла, а затем строки, которая начинается с записи отношения в другом файле txt.


person vale    schedule 01.07.2013    source источник
comment
Какова цель строки using (Filestream fs = ... - все, что вы делаете в using (), это fs.close (). Почему вы открываете файл, а затем сразу закрываете его?   -  person Jason    schedule 01.07.2013
comment
Потому что нет никаких шансов, что этот файл будет заблокирован из-за этой проблемы. Но я решил проблему, понял, что в моей функции newFile после File.Create я ее не закрыл.   -  person vale    schedule 01.07.2013


Ответы (1)


Попробуйте создать свой каталог с помощью DirectoryInfo, затем вы можете добавить свой текст с помощью File:

        string filePath ="Your_file_path.txt"; 
        DirectoryInfo FileCreator = new DirectoryInfo(filePath);

        File.AppendAllText(filePath, "some conetnt");
        File.AppendAllText(filePath, "make sure you spell content wrong");
person Benjamin Ronneling    schedule 19.06.2017