我有一个 Xml 文件,可以从 HDD 浏览到我的 C# 程序。现在,该 Xml 文档的节点显示在我的 winform 的树视图中。我现在所有的逻辑都在 winform 中。共有三种方法:
休息,我有各种按钮,例如浏览、展开树、清除。一切都在winform中。我的浏览按钮点击事件也在winform类中,这是显而易见的。
现在我要做的就是为业务逻辑创建一个单独的类,其中包括第 1 点和第 2 点中的方法。其余部分保留在 winform 类中。这个新课程位于同一个项目中。现在该项目有两个类 - 一个是 winforms,另一个是我用来存储我的业务逻辑的类,以便使前端类不受业务逻辑的影响。
我无法通过使用对象来做到这一点,但我必须利用在具有逻辑的类中提供文件路径。这样,该类就知道文件路径。 你知道我该怎么做吗?
请告诉我语法,因为我是新手。
如果您希望用户能够指定文件的路径,我相信您正在寻找 OpenFileDialog 组件。
如果没有,则只需将路径作为业务类逻辑中的参数传递即可:
public class MyBusinessLogic {
public MyBusinessLogic(String filePath) {
this.FilePath = filePath;
}
public String FilePath { get; private set; }
public void Process() {
// whatever you do here
}
}
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string filePath = @"C:\Path\To\Your\Directory\"; // Specify the directory path where your text files are stored
Console.WriteLine("Enter a case to load a text file (1, 2, 3, etc.):");
string input = Console.ReadLine();
string fileContent = LoadTextFile(filePath, input);
if (fileContent != null)
{
Console.WriteLine("File content:");
Console.WriteLine(fileContent);
}
else
{
Console.WriteLine("Invalid case or file not found.");
}
Console.ReadLine();
}
static string LoadTextFile(string directoryPath, string caseNumber)
{
string fileName;
switch (caseNumber)
{
case "1":
fileName = "file1.txt";
break;
case "2":
fileName = "file2.txt";
break;
case "3":
fileName = "file3.txt";
break;
// Add more cases as needed
default:
return null; // Invalid case
}
string filePath = Path.Combine(directoryPath, fileName);
if (File.Exists(filePath))
{
return File.ReadAllText(filePath);
}
else
{
return null; // File not found
}
}
}
enter code here