C#如何将openFileDialog中的txt文件放入数组scriptFile [] [] by line#,以及行字符串内容

时间:2018-06-05 22:28:19

标签: c# arrays openfiledialog

我正在尝试用C#创建一个工具。该工具允许用户逐行查看某些外语文本,并在下面的文本框中输入他们的人工翻译,提交并最终保存到新的文本文件。

我试图用openFileDialog打开一个.txt文件,然后通过for循环逐行发送,这将添加到一个二维数组中,有4件事:

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

Array的第一部分是Integer中的行号。 第二部分和第三部分是由TAB分隔的2个文本。

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

然后:

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

如果我能解决这个问题,那么其他一切都会立即落实到位。我一直在寻找解决方案,但我对C#的了解有限,因为我主要是一个Java / PHP人:/

到目前为止,我已将留置权计数下降,并继续将所有内容排序为数组。到目前为止,我有什么:

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";
        }
    }

3 个答案:

答案 0 :(得分:0)

我建议您将翻译作为一个课程,从长远来看,这将为您提供更好的服务。一个非常基本的类实现可能如下所示:

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
    }
}

答案 1 :(得分:0)

可能没有学习效果,但我想出来了。

注意这是非常原始的代码。没有异常处理。

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

答案 2 :(得分:0)

嗯,你已经收到了两个完整的答案,但我会发布我的看法,也许这将有助于找出正确的解决方案。

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;
}