none
Importing file using stream reader RRS feed

  • Question

  • This program is supposed to import text file from my folder which is in the projectName>bin>debug, but somehow the

    program isn't reading it. Can somebody help me point out the error? Thank you in advance for helping.

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class FileLoader : Form { List<string> itemSaver; StreamReader reader; public FileLoader() { InitializeComponent(); itemSaver = new List<string>(); reader = new StreamReader("texter.txt", Encoding.Default, false); } private void button1_Click(object sender, EventArgs e) { this.button1.Text = "Browse"; string item; if (File.Exists("texter.txt")) { reader = new StreamReader("texter.txt", Encoding.Default, false); while ((item = reader.ReadLine()) != null) { itemSaver.Add(item.ToString()); } foreach (string a in itemSaver) { string[] vektor = a.Split(new string[] { "###" }, StringSplitOptions.None); } } } }


    Wednesday, February 5, 2020 1:40 PM

Answers

  • I added a code sample in an existing GitHub repository. The example uses a comma but can be changed. This line of code requires changing from comma to your separator.

    Form code, reads a text file in the same directory as the executable and that can be changed also.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using FileLibrary;
    using FileLibrary.Classes;
    
    namespace ForumQuestion1
    {
        public partial class Form1 : Form
        {
            private string _FileName;
            private BindingSource _bindingSource = new BindingSource();
            public Form1()
            {
                InitializeComponent();
    
                _FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "customers.csv");
    
                // read lines into a list
                _bindingSource.DataSource = FileReader.ConventionalRead(_FileName);
                bindingNavigator1.BindingSource = _bindingSource;
    
                // data bind all properties except CustomerIdentifier
                CompanyNameTextBox.DataBindings.Add("Text", _bindingSource, "CompanyName");
                ContactNameTextBox.DataBindings.Add("Text", _bindingSource, "ContactName");
                ContactTitleTextBox.DataBindings.Add("Text", _bindingSource, "ContactTitle");
                CityTextBox.DataBindings.Add("Text", _bindingSource, "City");
                CountryTextBox.DataBindings.Add("Text", _bindingSource, "Country");
            }
    
            private void SaveButton_Click(object sender, EventArgs e)
            {
                var customers = (List<Customer>) _bindingSource.DataSource;
                var lines = customers.Select(customer => customer.LinesItems);
    
                File.WriteAllLines(_FileName,lines);
            }
        }
    }


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by MorenainHanoi Thursday, February 6, 2020 3:37 PM
    Thursday, February 6, 2020 3:11 PM
    Moderator
  • In this case you would have a class which represents the elements in a line. For instance lets say each line splits into three elements 

    You create a list

    List<LineItem> lineItemsList = new List<LineItem>();

    Of this class (adjust as needed)

    public class LineItem
    {
        public string Value1 { get; set; }
        public string Value2 { get; set; }
        public string Value3 { get; set; }
    }

    Once the list is populated create a BindingSource at form level variable

    private BindingSource _lineItemsBindingSource = new BindingSource();

    Assign the list to the BindingSource

    _lineItemsBindingSource.DataSource = lineItemsList;

    Create a TextBox for each property and data binding eg.

    Value1TextBox.DataBindings.Add("Text", _lineItemsBindingSource, "Value1");

    Add a BindingNavigator from the tool box e.g. in the case I use the default name bindingNavigator1 then assign the BindingSource to it

    bindingNavigator1.BindingSource = _lineItemsBindingSource;

    Delete from the BindingNavigator the add and delete buttons. At this point pressing the buttons permits movement up and down and a text box in the BindingNavigator shows which line you are on. Change a value in the text box changes the underlying property.

    Do you need to save changes? Let me know and I can assist with that too.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by MorenainHanoi Thursday, February 6, 2020 3:37 PM
    Thursday, February 6, 2020 1:24 PM
    Moderator
  • Okay this is for multiple textbox.  The program i did must show only 1 textbox which will show 1 row of string list at a time with each click.
    • Marked as answer by MorenainHanoi Thursday, February 6, 2020 3:37 PM
    Thursday, February 6, 2020 3:15 PM

All replies

  • This works for me

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class FileLoader : Form
        {
            List<string> itemSaver = new List<string>();
    
            private string fileName = "";
            public FileLoader()
            {
                InitializeComponent();
                fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "texter.txt");
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                button1.Text = "Browse";
                string item;
                var sb = new StringBuilder();
                
                if (File.Exists(fileName))
                {
                    var reader = new StreamReader("texter.txt", Encoding.Default, false);
                    while ((item = reader.ReadLine()) != null)
                    {
                        itemSaver.Add(item);
                    }
    
                    foreach (string a in itemSaver)
                    {
                        string[] vektor = a.Split(new[] { "###" }, StringSplitOptions.None);
                        sb.AppendLine(string.Join("-", vektor));
                    }
    
                    MessageBox.Show(sb.ToString());
                }
            }
        }
    }
    

    And one parameter for StreamReader

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class FileLoader : Form
        {
            List<string> itemSaver = new List<string>();
    
            private string fileName = "";
            public FileLoader()
            {
                InitializeComponent();
                fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "texter.txt");
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                button1.Text = "Browse";
                string item;
                var sb = new StringBuilder();
                
                if (File.Exists(fileName))
                {
                    var reader = new StreamReader("texter.txt");
                    while ((item = reader.ReadLine()) != null)
                    {
                        itemSaver.Add(item);
                    }
    
                    foreach (string a in itemSaver)
                    {
                        string[] vektor = a.Split(new[] { "###" }, StringSplitOptions.None);
                        sb.AppendLine(string.Join("-", vektor));
                    }
    
                    MessageBox.Show(sb.ToString());
                }
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Wednesday, February 5, 2020 2:23 PM
    Moderator
  • Thanks Karen, will definitely try this. :)
    Wednesday, February 5, 2020 2:37 PM
  • Hey Karen,

    It does work and it shows the whole file, but i have a text box which will supposed to show one row at a time when I click the button, what code should be used for it?

     -Morena

    Wednesday, February 5, 2020 5:17 PM
  • In this case you would have a class which represents the elements in a line. For instance lets say each line splits into three elements 

    You create a list

    List<LineItem> lineItemsList = new List<LineItem>();

    Of this class (adjust as needed)

    public class LineItem
    {
        public string Value1 { get; set; }
        public string Value2 { get; set; }
        public string Value3 { get; set; }
    }

    Once the list is populated create a BindingSource at form level variable

    private BindingSource _lineItemsBindingSource = new BindingSource();

    Assign the list to the BindingSource

    _lineItemsBindingSource.DataSource = lineItemsList;

    Create a TextBox for each property and data binding eg.

    Value1TextBox.DataBindings.Add("Text", _lineItemsBindingSource, "Value1");

    Add a BindingNavigator from the tool box e.g. in the case I use the default name bindingNavigator1 then assign the BindingSource to it

    bindingNavigator1.BindingSource = _lineItemsBindingSource;

    Delete from the BindingNavigator the add and delete buttons. At this point pressing the buttons permits movement up and down and a text box in the BindingNavigator shows which line you are on. Change a value in the text box changes the underlying property.

    Do you need to save changes? Let me know and I can assist with that too.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by MorenainHanoi Thursday, February 6, 2020 3:37 PM
    Thursday, February 6, 2020 1:24 PM
    Moderator
  • I added a code sample in an existing GitHub repository. The example uses a comma but can be changed. This line of code requires changing from comma to your separator.

    Form code, reads a text file in the same directory as the executable and that can be changed also.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using FileLibrary;
    using FileLibrary.Classes;
    
    namespace ForumQuestion1
    {
        public partial class Form1 : Form
        {
            private string _FileName;
            private BindingSource _bindingSource = new BindingSource();
            public Form1()
            {
                InitializeComponent();
    
                _FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "customers.csv");
    
                // read lines into a list
                _bindingSource.DataSource = FileReader.ConventionalRead(_FileName);
                bindingNavigator1.BindingSource = _bindingSource;
    
                // data bind all properties except CustomerIdentifier
                CompanyNameTextBox.DataBindings.Add("Text", _bindingSource, "CompanyName");
                ContactNameTextBox.DataBindings.Add("Text", _bindingSource, "ContactName");
                ContactTitleTextBox.DataBindings.Add("Text", _bindingSource, "ContactTitle");
                CityTextBox.DataBindings.Add("Text", _bindingSource, "City");
                CountryTextBox.DataBindings.Add("Text", _bindingSource, "Country");
            }
    
            private void SaveButton_Click(object sender, EventArgs e)
            {
                var customers = (List<Customer>) _bindingSource.DataSource;
                var lines = customers.Select(customer => customer.LinesItems);
    
                File.WriteAllLines(_FileName,lines);
            }
        }
    }


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by MorenainHanoi Thursday, February 6, 2020 3:37 PM
    Thursday, February 6, 2020 3:11 PM
    Moderator
  • Okay this is for multiple textbox.  The program i did must show only 1 textbox which will show 1 row of string list at a time with each click.
    • Marked as answer by MorenainHanoi Thursday, February 6, 2020 3:37 PM
    Thursday, February 6, 2020 3:15 PM
  • Okay this is for multiple textbox.  The program i did must show only 1 textbox which will show 1 row of string list at a time with each click.

    You never mentioned that until now. So here is what you must do, if everything other than placing all data into a TextBox works then mark my reply as answered then start a new question and I will provide a solution for the new requirement for showing all in one TextBox which I've already written. Or stop and figure it out yourself.

    The bottom line is when there are new requirements and the initial question as written has been answered its time to begin on the next part in a new question.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, February 6, 2020 3:35 PM
    Moderator