简体   繁体   中英

C# how to place txt file from openFileDialog into array scriptFile[][] by line#, and line string content

I am trying to create a tool in C#. The tool is to allow a user the ability to see some foreign language text line-by-line, and enter in their human translation in a text box below, submit, and eventually save to a new text file.

I am trying to open a .txt file with openFileDialog, then send line-by-line through a for loop that will add into a two dimensional array, 4 things:

Things we need:
        Array scriptFile[][]
            scriptFile[X][0] = Int holding the Line number
            scriptFile[X][1] = First line piece
            scriptFile[X][2] = Untranslated Text
            scriptFile[X][3] = Translated Text input

The first part of the Array is the line number in an Integer. The Second and third pieces are 2 pieces of text separated by a TAB.

Example Text File:
Dog 슈퍼 지방입니다.
cat 일요일에 빨간색입니다.
Elephant    적의 피로 위안을 찾는다.
Mouse   그의 백성의 죽음을 복수하기 위해 싸우십시오.
racoon  즉시 의료 지원이 필요합니다.

Which then:

So array: 
scriptFile[0][0] = 1
scriptFile[0][1] = Dog
scriptFile[0][2] = 슈퍼 지방입니다.
scriptFile[0][3] = "" (Later input as human translation)

If I can crack this, then everything else will just fall into place in no time. I'm continuing to look for solutions, but my knowledge of C# is limited since I'm mainly a Java/PHP guy :/

So far I have the lien count down, and continuing to work on sorting everything into an array. So far what I kind of have:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.continueButton.Click += new System.EventHandler(this.continueButton_Click);
        }
        private void continueButton_Click(object sender, EventArgs e)
        {
            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(openFile.FileName);
                var lineCount = File.ReadLines(openFile.FileName).Count();
                MessageBox.Show(lineCount.ToString());
                sr.Close();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            openFile.Filter = "Text files (.txt)|*.txt";
        }
    }

I would suggest making your translations a class, in the long run this will serve you much better. A very basic class implementation might look something like this:

public class Translation
{
    public int Id { get; set; }
    public string Text { get; set; }
    public string TranslatedText { get; set; }

    public Translation()
    {

    }

    public IEnumerable<Translation> ReadTranslationFile(string TranslationFileName)
    {
        var translations = new List<Translation>();

        //implement reading in text file

        return translations;
    }

    public void WriteTranslationFile(string TranslationFileName, List<Translation> Translations)
    {
        //implement writing file
    }
}

There is probably no learning effect but i figured it out.

NOTE This is very raw code. There is no exception handling.

using System;
using System.IO;
using System.Threading.Tasks;  
using System.Windows.Forms;

namespace TextArrayManipulation
{ 
    public partial class Form1 : Form
    {
        private TaskCompletionSource<string> _translationSubmittedSource = new TaskCompletionSource<string>();

        private string[,] _result;

        public Form1()
        {
            InitializeComponent();
        }

        private async void buttonOpen_Click(object sender, EventArgs e)
        {
            using (var ofd = new OpenFileDialog())
            {
                if (ofd.ShowDialog() != DialogResult.OK) return;

                _result = new string[File.ReadLines(openFile.FileName).Count(), 4];

                using (var streamReader = new StreamReader(ofd.FileName))
                {
                    var line = string.Empty;
                    var lineCount = 0;
                    while (line != null)
                    {
                        line = streamReader.ReadLine();

                        if (string.IsNullOrWhiteSpace(line)) continue;

                        // update GUI
                        textBoxLine.Text = line;
                        labelLineNumber.Text = lineCount.ToString();

                        // wait for user to enter a translation
                        var translation = await _translationSubmittedSource.Task;

                        // split line at tabstop
                        var parts = line.Split('\t');
                        // populate result
                        _result[lineCount, 0] = lineCount.ToString();
                        _result[lineCount, 1] = parts[0];
                        _result[lineCount, 2] = parts[1];
                        _result[lineCount, 3] = translation;

                        // reset soruce
                        _translationSubmittedSource = new TaskCompletionSource<string>();
                        // clear TextBox
                        textBoxTranslation.Clear();
                        // increase line count
                        lineCount++;
                    }
                }
                // proceede as you wish...
            }
        }

        private void buttonSubmit_Click(object sender, EventArgs e)
        {
            _translationSubmittedSource.TrySetResult(textBoxTranslation.Text);
        }
    }
}

Well, you've received already two full answers, but i'll post my take anyways, maybe it will be helpful in figuring out the right solution.

public void Main()
{
    List<LineOfText> lines = ReadTextFile("file.txt");

    // Use resulting list like this
    if (lines.Count > 0)
    {
        foreach (var line in lines)
        {
            Console.WriteLine($"[{line.LineNumber}] {line.FirstLinePiece}\t{line.UntranslatedText}");
        }
    }
}

class LineOfText
{
    public int LineNumber { get; set; }
    public string FirstLinePiece { get; set; }
    public string UntranslatedText { get; set; }
    public string TranslatedText { get; set; }
}

private List<LineOfText> ReadTextFile(string filePath)
{
    List<LineOfText> array = new List<LineOfText>();

    using (StreamReader sr = new StreamReader(filePath))
    {
        // Read entire file and split into lines by new line or carriage return symbol
        string[] lines = sr.ReadToEnd().Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
        // Parse each line and add to the list
        for (int i = 0; i < lines.Length; i++)
        {
            int tabIndex = lines[i].IndexOf('\t');
            string firstPiece = lines[i].Substring(0, tabIndex);
            string restOfLine = lines[i].Substring(tabIndex + 1);

            array.Add(new LineOfText()
            {
                LineNumber = i,
                FirstLinePiece = firstPiece,
                UntranslatedText = restOfLine
            });
        }
    }

    return array;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM