LoginSignup
02Igarashi01
@02Igarashi01

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

System.IO.IOException:

解決したいこと

本来はファイルが存在しない場合ファイルを生成して読み込み、既にファイルが存在する場合読み込んで既存の情報に新たに入力した情報を書き加える物ですが、既にファイルが存在手てる時、エラーが発生して「別のプロセスが使用している為アクセス出来ない」て云われる。
原因が全く分からない

発生している問題・エラー

System.IO.IOException:

スクリーンショット 2023-01-25 192901.png

該当するソースコード

public class Base : IPessoa
    {
        public Base(string nome, string telefone, string cpf)
        {
            Nome = nome;
            Telefone = telefone;
            CPF = cpf;
        }

        public Base() { }

        public string Nome;
        public string Telefone;
        public string CPF;

        public void SetNome(string nome) { Nome = nome; }
        public void SetTelefone(string telefone) { Telefone = telefone; }
        public void SetCPF(string cpf) { CPF = cpf; }

        public virtual void Gravar()
        {
            var dados = Ler();
            dados.Add(this);

            StreamWriter r = new StreamWriter(diretorioArquivo());
            r.WriteLine("nome;telfone;cpf");
            foreach (Base b in dados)
            {
                var linha = $"{b.Nome};{b.Telefone};{b.CPF}";
                r.WriteLine(linha);
            }
            r.Close();
        }

        public virtual List<IPessoa> Ler()
        {
            var dados = new List<IPessoa>();
            if (File.Exists(diretorioArquivo()))
            {
                StreamReader arquivo = File.OpenText(diretorioArquivo());
                string linha;
                int i = 0;
                while ((linha = arquivo.ReadLine()) != null)
                {
                    i++;
                    if (i == 1) continue;
                    var baseArquivo = linha.Split(';');

                    var b = (IPessoa)Activator.CreateInstance(GetType());
                    b.SetNome(baseArquivo[0]);
                    b.SetTelefone(baseArquivo[1]);
                    b.SetCPF(baseArquivo[2]);
                    dados.Add(b);
                }
            }
            return dados;
        }

        internal string diretorioArquivo()
        {
            return ConfigurationManager.AppSettings["CaminhoArquivo"] + GetType().Name + ".txt";
        }
    }

自分で試したこと

パスを変えてみた
パソコンを再起動してみた
0

StreamReader arquivo = File.OpenText(diretorioArquivo());
こいつがCloseされていないから?

3

特に理由が無ければusingを使うことをお勧めします。
https://learn.microsoft.com/ja-jp/dotnet/api/system.io.streamwriter?view=net-7.0
closeが不要になり、リソースの解放漏れが発生しなくなります。

2

有難う解決しました

0

Your answer might help someone💌