我正在建立数据库,而我的系统存在一个小问题:我只能读取整个文件(不能读取变量),但可以将变量写入文件中,但是我也需要能够编辑文件。我可以编辑它,但是我想自己编辑部分,而不必打开整个文件进行编辑/仅在部分中替换整个文件中的给定字符串。
我想问用户他们将更改文件中的哪一部分,但是我的脚本更改了赋予整个文件的所有字符串。
所以这就是我想要的:
选择文件->选择要编辑的节/行->输入数据->将数据保存到行
该文件如下所示:
Name: Kim jr.
Age: 1980/05/20
Gender: Male
Status: Single
Weight: 46.2 Kg
Friends: Unknown
Notes:
This is a dummy file, used for testing.
这是我的代码当前的样子:
Console.Clear();
string[] fileArray = Directory.GetFiles(@"C:\Nova_Files\Database"); //slecets the files in the folder
if (fileArray.Length < 1)
{
Console.WriteLine();
Console.WriteLine("There are no files in the database for deleting");
Console.ReadLine();
}
else
{
Console.WriteLine("Here is a list of the files in the database, please select a file to edit.\n");
foreach (string name in fileArray) //shows the files in the folder.
{
Console.WriteLine(name);
}
Console.WriteLine();
userValue = Console.ReadLine();
string filename = userValue;
foreach (string x in fileArray)
{
if (x.Contains(filename))
{
Console.WriteLine();
Console.WriteLine(filename + " Was selected for editing");
Console.WriteLine();
Console.WriteLine("Press anykey to continue");
Console.ReadLine();
Console.Clear();
Console.WriteLine("The current editing " + filename);
Console.WriteLine("The File [" + filename + "] Contains This:\n");
string text = System.IO.File.ReadAllText(@"C:\Nova_Files\Database\" + filename);
Console.WriteLine(text);
Console.WriteLine();
Console.WriteLine("What do you want to edit?");
userValue = Console.ReadLine();
string needOfEdit = userValue;
Console.WriteLine();
Console.WriteLine("What will you replace " + needOfEdit + " With?");
userValue = Console.ReadLine();
string replacement = userValue;
File.WriteAllText(@"C:\Nova_Files\Database\" + filename, File.ReadAllText(@"C:\Nova_Files\Database\" + filename).Replace(needOfEdit, replacement));
text = System.IO.File.ReadAllText(@"C:\Nova_Files\Database\" + filename);
Console.WriteLine(text);
Console.Read();
如果您不介意引入Microsoft.VisualBasic
程序集,则可以通过随机文件访问获得所需的内容:
https://msdn.microsoft.com/zh-CN/library/aa711474(v=vs.71).aspx
在C#中引用程序集后,MSDN链接中描述的文件操作(例如FileOpen
)在FileSystem
该类中。 - IEFileSystem.FileOpen()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句