用C#中的同一文本文件的另一行替换一行

时间:2014-03-18 23:28:14

标签: c#

我想根据一些数据用文件的现有行替换文本行。我开发了一些代码块,但它没有用。 我的文本文件是这样的: -

g_start-fd,g_start-cnst,g_start-eq,mv-mv_size,mv-mv_alloy,mv-mv_argmt,mv-mv_ps,xfrmr-kva,g_end-line_t,g_end-str_num,g_end-cmt,g_end-str_coord-Latitude,g_end-str_coord-Longitude
28F1Y,oh,mv oh,120,al,oh_3,P45R24,,i,P45R25,,9.53725695,-0.86668464
28F1Y,oh,mv oh,120,al,oh_3,P45R25,,i,P45R42,,9.5468355,-0.85948875
28F1Y,oh,mv oh,120,al,oh_3,P45R42,,i,P45R49,,9.55073989,-0.85625858
28F1Y,oh,mv oh,120,al,oh_3,P45R49,,a,P45R25,,,
28F1Y,oh,mv oh,120,al,oh_3,P45R54,,i,P45R55,,9.5544981,-0.85359626
28F1Y,oh,mv xfrmr,120,al,oh_3,P45R55,5000,e,P45R56,Substation,9.5549907,-0.85303108
28F1Y,ug,mv,185,al,xlpe_3,P45R56,,e,P45R55,,,
28F1Y,ug,mv,185,al,xlpe_3,P45R57,,s,P45R58,Take off from ring main,9.55387622,-0.8538622
28F1Y,oh,mv oh,120,al,oh_3,P45R58,,a,P45R73,,9.54513187,-0.86060037
28F1Y,oh,mv oh,120,al,oh_3,P45R73,,a,P45R77,,9.5417936,-0.86098952
28F1Y,oh,mv oh,120,al,oh_3,P45R77,,a,P45R80,,9.54144045,-0.85857346
28F1Y,oh,mv oh,120,al,oh_3,P45R80,,a,P45R86,,9.53675765,-0.85935176
28F1Y,oh,mv,120,al,oh_3,P45R86,,e,P45R80,,,

我的应用程序在运行此代码时停止工作:

string fileName1 = "D:\\WriteTextWork\\Line1.txt"; ;

OpenFileDialog pfdg = new OpenFileDialog();
if (pfdg.ShowDialog() == DialogResult.OK)
{
    fileName1 = pfdg.FileName;
}

if (File.Exists(fileName1))
{
    StreamReader SR = new StreamReader(fileName1);

    string Data = null;
    int count = 0;

    while ((Data = SR.ReadLine()) != null)
    {
        count++;
        if (count > 1)
        {
             string CopyText = "";
            String[] SplitData = Data.Split(',');
            if (SplitData[9] != null && SplitData[11] != null)
            {
                CopyText = Data;
                string data1 = SR.ReadLine();
                //MessageBox.Show(CopyText);
            }
            using (StreamReader SR1 = new StreamReader(fileName1))
            {
                //var SW = new StreamWriter(resultString1);
                string line;
                while ((line = SR1.ReadLine()) != null)
                {


                    //String TrimData2 = line.Trim();
                    String[] SplitText = line.Split(',');
                    if (SplitText[9] == SplitData[9] && SplitText[11] == null)
                    {
                        using (StreamWriter SW = new StreamWriter(resultString1))
                        {
                            SW.WriteLine(CopyText);
                            MessageBox.Show(CopyText);
                            SW.Close();
                        }

                    }
                }
                SR1.Close();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

要强制您的代码工作,只需替换:

if (SplitText[9] == SplitData[9] && SplitText[11] == null)

要:

if (SplitText[9] == SplitData[9] && SplitText[11] == String.Empty)

因为SplitText [11]在您共享的文件中的所有情况下永远不会为空。

答案 1 :(得分:0)

我做了一个事件(btn_proceed_Click)来继续这个方法,你可以把他(方法)放在你想要的任何地方。这是完整的代码,只需用你的代码替换它:

    private void btn_proceed_Click(object sender, EventArgs e)
    {
        // This dictionary contains indices of rows we need to replace.
        Dictionary<int, int> replaceable = new Dictionary<int, int>();
        replaceable.Add(4, 1);
        replaceable.Add(7, 5);
        replaceable.Add(13, 11);

        string input = String.Empty;
        OpenFileDialog pfdg = new OpenFileDialog();
        if (pfdg.ShowDialog() == DialogResult.OK)
        {
            input = pfdg.FileName;
        }
        // I placed the result into the another file called result.txt. You can use output path as same as input to overwrite the file.
        ReplaceLines(replaceable, input, @"C:\Users\Wallstrider\Documents\Visual Studio 2010\Projects\result.txt", 9);
    }
    /// <summary>
    /// Replaces lines of the file depends on 9th item is exist.
    /// </summary>
    /// <param name="replaceable">Rows incides to replace.</param>
    /// <param name="input_path">Path to the input file.</param>
    /// <param name="output_path">Path to the output file.</param>
    /// <param name="has_value_index">Index of a split data value in the row.</param>
    private void ReplaceLines(Dictionary<int, int> replaceable, string input_path, string output_path, int has_value_index)
    {
        if (File.Exists(input_path))
        {
            string file;
            file = new StreamReader(input_path).ReadToEnd();

            string[] lines = file.Split(new char[] { '\n' });
            List<string[]> split_data = new List<string[]>();

            for (int i = 0; i < lines.Length; i++)
                split_data.Add(lines[i].Split(','));

            List<int> allowed_for_replace_indices = new List<int>();
            List<int> not_allowed_for_replace_indices = new List<int>();

            // Check if the row has the value of 9th item then we are allowed to replace rows.
            for (int i = 1; i < split_data.Count; i++)
            {
                if (split_data[i][has_value_index] != String.Empty)
                    allowed_for_replace_indices.Add(i);
                else
                    not_allowed_for_replace_indices.Add(i);
            }
            List<int> rows_replaced = new List<int>();
            List<int> rows_not_replaced = new List<int>();
            // Loop through our replaceable indices dictionary.
            for (int i = 0; i < replaceable.Count; i++)
            {
                int key = replaceable.ElementAt(i).Key;
                int value = replaceable.ElementAt(i).Value;
                // if both rows have 9th item then we can start replacement.
                if (allowed_for_replace_indices.Contains(key) && allowed_for_replace_indices.Contains(value))
                {
                    string temp = lines[value];
                    lines[value] = lines[key];
                    lines[key] = temp;
                    rows_replaced.Add(key);
                    rows_replaced.Add(value);
                }
                else
                {
                    rows_not_replaced.Add(key);
                    rows_not_replaced.Add(value);
                }
            }

            using (StreamWriter sw = new StreamWriter(output_path))
            {
                for (int i = 0; i < lines.Length; i++)
                    sw.WriteLine(lines[i]);
                sw.Flush();
                sw.Close();
            }

            MessageBox.Show("Rows replaced: " + String.Join("; ", rows_replaced.ToArray()) + " .\nRows not replaced: " + String.Join("; ", rows_not_replaced.ToArray()) + ".\nComplete.");
        }
    }

以下代码将替换(我从零开始计算)4,1; 7,5; 13,11;如果我理解你的逻辑,如果每个都有第9个项目。