Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用C语言中相同文本文件的另一行替换一行#_C# - Fatal编程技术网

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

C# 用C语言中相同文本文件的另一行替换一行#,c#,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,

我想根据一些数据用文件的现有行替换文本行。我已经开发了一些代码块,但它不起作用。 我的文本文件如下所示:-

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

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

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

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

我制作了一个事件(btn\u继续\u单击)来继续该方法,您可以将他(方法)放在任何您想要的地方。以下是完整的代码,请用您的代码替换:

    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.");
        }
    }
private void btn\u继续\u单击(对象发送者,事件参数e)
{
//此词典包含我们需要替换的行的索引。
字典可替换=新字典();
可替换。添加(4,1);
可替换。添加(7,5);
可替换。添加(13,11);
字符串输入=string.Empty;
OpenFileDialog pfdg=新建OpenFileDialog();
if(pfdg.ShowDialog()==DialogResult.OK)
{
输入=pfdg.FileName;
}
//我将结果放入另一个名为result.txt的文件中。您可以使用与输入相同的输出路径来覆盖该文件。
替换行(可替换,输入,@“C:\Users\Wallstrider\Documents\Visual Studio 2010\Projects\result.txt”,9);
}
/// 
///替换文件的行取决于第9项是否存在。
/// 
///行包括替换。
///输入文件的路径。
///输出文件的路径。
///行中拆分数据值的索引。
私有void ReplaceLines(字典可替换、字符串输入路径、字符串输出路径、int有值索引)
{
if(File.Exists(输入路径))
{
字符串文件;
file=新的StreamReader(输入路径).ReadToEnd();
string[]line=file.Split(新字符[]{'\n'});
列表拆分_数据=新列表();
对于(int i=0;i

以下代码将替换(从零开始计数)4,1;7, 5; 13, 11; 如果我正确理解您的逻辑,则每行都有第9项。

您能发布错误以及代码的哪一部分引发错误吗?“停止工作”不是对所发生情况的技术描述。如果你需要帮助,你需要学会像程序员一样思考,进行一些技术观察,然后在问题中报告这些细节。你正在创建嵌套的读卡器和编写器。想想看,这有意义吗?考虑1个读者和1个作家在同一水平和复制线符合你的逻辑。告诉我你需要替换哪些数据?我会帮忙的。它冻结了我的应用程序,我是C#新手,这就是为什么我不知道如何一步一步地调试。是的,我考虑过嵌套的读者和作者,但我能想出如何进行更正@Wallstrider:我需要根据第二行“P45R25”、“P45R42”、“P45R49”中的第9项,将第5行替换为第2行,将第8行替换为第6行,将第14行替换为第12行。。。谢谢大家的反馈…这里是你可以下载项目来测试代码的方法。名为WindowsFormsApplicationHelp1的存档。@Wallstrider。。。。非常感谢你的帮助。它工作得很好。另一件事是,若我不知道哪一行需要根据每行的第9项进行替换(这意味着若它是一个大的文本文件!!!)。再次非常感谢。。。。我用另一种方式来思考我的问题,你的解决方案。。。。。谢谢
    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.");
        }
    }