首页 > 解决方案 > 我正在尝试读取我创建的文本文件中的最后一行,并在程序退出之前将最后一行添加到我的文件名中

问题描述

基本上,如果我创建的文件中有 4,5,6。我需要读取文件,取出数字 6 并将其添加到我的文件名 Ex:(Test-6.txt) 是的,我还想在文件进入目录之前添加破折号。我可以在这里得到一些指导吗?

    private void BegPinNum_KeyUp(object sender, KeyEventArgs e)
    {
        FileName2.Text = BegPinNum.Text;
    }
     private void FileName2_TextChanged(object sender, EventArgs e) 
    {
        //This is the textbox that displays the filename in it, right now whatever I type in 
          BegPinNum automatically displays here but the rest of the filename I want to get from the 
          last line in the file I created later on in the code
    }

这之间有一些代码用于另一个文本框,不认为我需要它

        using (StreamWriter objWriter = new StreamWriter(var1))//I know StreamReader is used for 
              reading the file and I have tried some things but had no luck
             {

                    int numpins = int.Parse(Pins.Text);
                    string basepin = BegPinNum.Text;
                    int pinlength = basepin.Length;
                    string formatspecifier = "{0:d" + pinlength.ToString() + "}" + "{1}";
                    long pinnumber = long.Parse(basepin);
                    string dig = BegPinNum.Text;
                    string result = GetCheckDigit(dig);

                    for (int d = 0; d < numpins; d++)
                    {
                        if (String.IsNullOrEmpty(dig))
                        {
                            throw new Exception("null value not allowed");
                        }
                        else
                        {
                            dig = pinnumber.ToString();
                            result = GetCheckDigit(dig);
                        }

                        basepin = string.Format(formatspecifier, pinnumber, result);
                        objWriter.WriteLine(basepin);
                        pinnumber++;
                    }

                    objWriter.Close();  
                    MessageBox.Show("File has been created");
                }

          }
    }

标签: c#

解决方案


这应该可以帮助您入门:

string oldFile = "Test.txt";
string number = File.ReadAllLines(oldFile).Last();
string fileName = Path.GetFileNameWithoutExtension(oldFile);
string fileExt = Path.GetExtension(oldFile);
string newFile = $"{fileName}-{number}.{fileExt}";

File.Copy(oldFile, newFile);

推荐阅读