File close

1

I need to leave the file free, without being in use because it is barring. Here is 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. And if I do:

arquivo.Dispose();

It works, but it does not monitor the folder, I do not understand why this happens, the tracking 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;

This is the code that is either in the Created or Changed event, it does not execute.

 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 it, so that the file is free to be treated, and that the monitoring keeps working?

    
asked by anonymous 18.08.2017 / 14:09

1 answer

1

You should open the resources so that they close themselves, something like this:

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
}

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

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

    
18.08.2017 / 14:22