Manipulation of TXT files in C#

Asked

Viewed 971 times

1

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

File line

47030787838357RaNgEr6516/11/2016Paulo Ricardo de Souza 531156916 Normal 1-Admin

File opening and Variable assignment

    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);
                 }
             }
         }
//...
     }

O layout da tela está em anexo

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

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 library Filehelpers to read your file to a list of objects. Each file insertion produces a new object.

The Filehelpers has some methods to save a DataTable for formats such as CSV.

Browser other questions tagged

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