File closure

Asked

Viewed 136 times

1

I need to leave the file free, without getting in use, because it is blocking. Follow the code:

StringWriter sw = new StringWriter();
XmlTextWriter tw = new XmlTextWriter(sw);

XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
xsn.Add("", "http://www.portalfiscal.inf.br/nfe");

XmlSerializer ser = new XmlSerializer(typeof(TNFe));
FileStream arquivo = new FileStream("C:\\" + chave_nfe + "-NFe.xml", FileMode.CreateNew);

ser.Serialize(arquivo, nfe, xsn);

If I do:

sw.Close();

The file is still in use, and does not work as expected. What if I do:

arquivo.Dispose();

It works, only it does not monitor the folder, do not understand why this occurs, the monitoring code is soon after:

 form = new FormProgressBar();
 form.Show();

 int X = 6000;
 form.MaximumBar(X);

 // Faço o laço para atualizar a barra
 for (int i = 0; i < X; i++)
 {
       // Método que atualiza a barra e o texto da barra
       form.AtualizaBarra("Aguarde...");
       // Insiro algum código que desejo e vou mostrando o status da atualização
 }

 // clsdb.ExecutaSQL("insert into nfe (n_nota, chave) values ('" + txtnumero.Text + "','" + digito(chave) + "')");
 messagebox = 0;
 messageboxxml = 0;

 #region MONITORAR PASTA

 //Dizemos agora se é para monitorar os subdiretórios ou não
 fsw.IncludeSubdirectories = false;

 //Através de um Enum dizemos quais eventos devem ser monitorados, modificação da data do arquivo, tamanho, etc...
 fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;

 //Dizemos quais tipos de arquivos devem ser monitorados, *.*, *.xml, *.txt, etc...
 //fsw.Filter = "*.xml";
 //fsw.Filter = "*.ERR";

 //Definimos agora os eventos a serem gerados
 fsw.Created += new FileSystemEventHandler(fsw_Created);
 fsw.Changed += new FileSystemEventHandler(fsw_Changed);
 fsw.Error += new ErrorEventHandler(fsw_Error);

 // A propriedade abaixo define que a monitoração deve iniciar, se false, a pasta não será monitorada
 fsw.EnableRaisingEvents = true;

That’s the code that gets both in the event Created or Changed, he does not perform.

 FileInfo fileinfo = new FileInfo(e.FullPath);

 while (arquivoTravado(fileinfo))
 {
      Thread.Sleep(1000);
 }

 System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();

 xmldoc.Load(e.FullPath);

 if (e.FullPath.Length == 97)
 {
     System.Xml.XmlNode DadosLote = xmldoc.SelectSingleNode("DadosLoteNfe");
     System.Xml.XmlNode NumeroLote = DadosLote.SelectSingleNode("NumeroLoteGerado");

     string nlote = NumeroLote.InnerText;
     clsdb.ExecutaSQL("update nfe set num_lote = '" + nlote + "' where n_nota = '" + txtnumero.Text + "'");
  }

How can I do, so that the file is free to be treated, and the monitoring continues to work?

  • you’ve tried using a block using ?

  • No, I’ll try. Thank you.

  • Pay attention to how the code should be placed in the question for the next few times. Do not create code snippets for c#, for example.

  • I’m sorry for the mistake.

  • 1

    is using the FileSystemWatcher correct ? I believe you are using it wrong. If the file has not yet been closed, it must be firing the event fsw_Changed and appears to be working for you. If you close the file, it will not trigger the event fsw_Created because the file was created before the event was associated with fsw. It would be nice if you put in the full code and without these breaks so you can understand what you’re really doing

1 answer

1


You must open the resources deform that it close itself, something like that:

using (var sw = new StringWriter())
using (var tw = new XmlTextWriter(sw))
using (var arquivo = new FileStream("C:\\" + chave_nfe + "-NFe.xml", FileMode.CreateNew) {
    // ... faz o que deve aqui
}

In C# 8 you can already do:

using var sw = new StringWriter());
using var tw = new XmlTextWriter(sw));
using var arquivo = new FileStream("C:\\" + chave_nfe + "-NFe.xml", FileMode.CreateNew);
// ... faz o que deve aqui

I put in the Github for future reference.

There are errors in the use of the form to access the database (if you take the comment), but these are other problems, it would be too broad to answer this, ask new questions.

The problem of not monitoring may be related to the fact of not having the file closed, if it is not is another problem too, and we would need more information in new question to help properly, would have to see how this pa creating monitoring, what is occurring, as tested, etc.

  • The problem, that when I don’t use the close-up or Disposis, the monitoring works, it just doesn’t work when I use it. I’ll take the test with the using, to see if it works as expected.

  • 1

    It works by coincidence, because it’s not the right way. First you need to make the right use of the file and then see why the monitoring doesn’t work when the rest is right. But when you ask about it, be sure to put all the information that can help people help you.

  • I tried the way that helped me, using, works, generates the file and releases it, but the folder is not being monitored, I will update the question with the monitoring code.

  • Sorry for the mistake, it worked yes, I only changed the monitoring of place in the code, because I did the debug and I was not entering it, so it was just change, and it was the way I needed, thank you very much for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.