c# - 我正在尝试读取我创建的文本文件中的最后一行,并在程序退出之前将最后一行添加到我的文件名中
问题描述
基本上,如果我创建的文件中有 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");
}
}
}
解决方案
这应该可以帮助您入门:
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);
推荐阅读
- go - 当请求正文是对象数组时,绑定验证不起作用
- python-3.x - 修改并运行nose Doctest Plugin
- firebase - 如何确定所有事件都有“会话信息”,例如 ga_session_id、ga_session_number 在新的属性 APP+WEB 中用于 GA
- list - 来自未来
- > 列出
用于在常规函数/脚手架中使用的 API 调用 - php - 使用 jQuery 和 PHP 处理表单验证错误,PHP 未加载
- javascript - 用 C/C++ 编写的设备固件可以使用 SignalR 从 Web 服务器接收推送通知吗?
- c++ - 我在动态分配的数组中丢失了元素
- c - 已经审查了几个答案,但仍然没有在 C 中获得权力
- r - R - 如何根据某个日期和字符串对所有值求和?
- javascript - 在不重新加载页面的情况下无法获得正确的输入值