TXT file manipulation in C #

1

I'm working on a project where I need to perform User Registration and Control from an initial user (administrator). In my file I have the following line containing all the user information and in the code of the program, I assign them in a structure. Below are descriptions.

File line

  

Opening the file and Assigning variables

    private void BTNabrir_arquivo_Click(object sender, EventArgs e)
    {
         using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Title = "Selecione o arquivo para autenticação";
                openFileDialog.InitialDirectory = @"c:\Desktop\Projeto Integrado B (30-11)";
                openFileDialog.Filter = "txt files (*.txt)|*.txt";
                openFileDialog.FilterIndex = 2;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    Projeto_Integrado_B.Classe_Auxiliar.arquivo = openFileDialog.FileName;
                    //TXTresultado.Text = openFileDialog.FileName;
                }
                BTNconfirmar.Enabled = true;   
         }
         if (String.IsNullOrEmpty(Projeto_Integrado_B.Classe_Auxiliar.arquivo)) //Para arquivos nulos
         {
             MessageBox.Show("Arquivo Inválido! Selecione o arquivo para leitura.",
                 "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         else
         {
             // cria um leitor e abre o arquivo, para ler linha por linha
             using (StreamReader linha = new StreamReader(Projeto_Integrado_B.Classe_Auxiliar.arquivo))
             {
                 while ((autenticação = linha.ReadLine()) != null && autenticação.Length > 2)
                 {                        
                     // na última linha existe um caracter especial que indica EOF (end of file)
                     TXTresultado.Text += autenticação + '\r' + '\n';   //mensagem é visualizada na tela.   \r\n pula pra linha de baixo.

                     REGuser.CPF = Decimal.Parse(autenticação.Substring(0, 11));
                     REGuser.senha = autenticação.Substring(11, 11);
                     REGuser.data = Convert.ToDateTime(autenticação.Substring(22, 10));
                     REGuser.nome = autenticação.Substring(32, 30);
                     REGuser.RG = Decimal.Parse(autenticação.Substring(62, 10));
                     REGuser.status = autenticação.Substring(72, 13);
                     REGuser.perfil = autenticação.Substring(85, 15);
                 }
             }
         }
//...
     }
  

Is there any way for the program to skip a line and use TextBox's content to generate a new user and / or modify existing user information also using TextBox's content? If not, what do you suggest?

    
asked by anonymous 13.12.2016 / 01:07

1 answer

1

You can convert the text file to a DataSet and save the DataSet back to text. Here's how to use the following Helper :

public class TextToDataSet
{
    public TextToDataSet() { }

    /// <summary>
    /// Converts a given delimited file into a dataset. 
    /// Assumes that the first line    
    /// of the text file contains the column names.
    /// </summary>
    /// <param name="File">The name of the file to open</param>    
    /// <param name="TableName">The name of the 
    /// Table to be made within the DataSet returned</param>
    /// <param name="delimiter">The string to delimit by</param>
    /// <returns></returns>  
    public static DataSet Convert(string File,
     string TableName, string delimiter)
    {
        //The DataSet to Return
        DataSet result = new DataSet();

        //Open the file in a stream reader.
        StreamReader s = new StreamReader(File);

        //Split the first line into the columns       
        string[] columns = s.ReadLine().Split(delimiter.ToCharArray());

        //Add the new DataTable to the RecordSet
        result.Tables.Add(TableName);

        //Cycle the colums, adding those that don't exist yet 
        //and sequencing the one that do.
        foreach (string col in columns)
        {
            bool added = false;
            string next = "";
            int i = 0;
            while (!added)
            {
                //Build the column name and remove any unwanted characters.
                string columnname = col + next;
                columnname = columnname.Replace("#", "");
                columnname = columnname.Replace("'", "");
                columnname = columnname.Replace("&", "");

                //See if the column already exists
                if (!result.Tables[TableName].Columns.Contains(columnname))
                {
                    //if it doesn't then we add it here and mark it as added
                    result.Tables[TableName].Columns.Add(columnname);
                    added = true;
                }
                else
                {
                    //if it did exist then we increment the sequencer and try again.
                    i++;
                    next = "_" + i.ToString();
                }
            }
        }

        //Read the rest of the data in the file.        
        string AllData = s.ReadToEnd();

        //Split off each row at the Carriage Return/Line Feed
        //Default line ending in most windows exports.  
        //You may have to edit this to match your particular file.
        //This will work for Excel, Access, etc. default exports.
        string[] rows = AllData.Split("\r\n".ToCharArray());

        //Now add each row to the DataSet        
        foreach (string r in rows)
        {
            //Split the row at the delimiter.
            string[] items = r.Split(delimiter.ToCharArray());

            //Add the item
            result.Tables[TableName].Rows.Add(items);
        }

        //Return the imported data.        
        return result;
    }
}

Or, even better, you can use the FileHelpers library to read your file for a list of objects. Each file insert produces a new object.

FileHelpers has some methods to also save a DataTable to formats like CSV .     

13.12.2016 / 04:36