Trying to send a file to another class in C#

2019-08-05 20:12发布

问题:

as the title suggests im trying to send a file acquired by stream reader to another class so that that class can extract the information from it. I have tried extracting it within the form but this makes it confusing and im certain is a poor way of doing it. Can anyone suggest a way?

Here is the class that identifies the file..

namespace DistanceEstimatorFinal
{
    public partial class Form1 : Form


        private void openDataListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "CSV files (*.csv)|*.csv|Text files ( *.txt)|*.txt |All files (*.*)|*.*";
            if (ofd.ShowDialog(this).Equals(DialogResult.OK))
            {
                Stream fileStream = ofd.OpenFile();

                using (StreamReader reader = new StreamReader(fileStream))
                {

                }
            }
        } 

Now I need some way of sending it here... I can't see how :[

namespace DistanceEstimatorFinal
{

    public class dataPoints
    {
        List<dataPoint> Points;
        public dataPoints( )
        {
            Points = new List<dataPoint>();
            TextReader tr = new StreamReader();
            string input;
            while ((input = tr.ReadLine()) != null)
            {
                string[] bits = input.Split(',');
                dataPoint a = new dataPoint(bits[0],bits[1],bits[2]);              
                Points.Add(a);  


            }

            tr.Close();
        }

        internal dataPoint getItem(int p)
        {
            if (p < Points.Count)
            {
                return Points[p];
            }
            else
                return null;
        }
    }

}

Any help would be greatly appreciated

回答1:

I would just pass the path of the file to your class and then open the file for reading.

if (ofd.ShowDialog(this).Equals(DialogResult.OK))
{
    var path = ofd.FileName;

    //Pass the path to the dataPoints class and open the file in that class.
}

You could pass the path in the constructor of the class or to the method itself as a parameter.



回答2:

The job of the UI is really just to figure out what file needs to be processed.

I would have the business object that is doing the actual processing also create the StreamReader.

If you do not follow that approach, your UI is responsible for cleaning up a resource (the StreamReader) that it does not itself use.

Also, by separating the processing entirely away from the event handler in your UI, you make it easier to process the file on a separate thread if that becomes necessary in the future.