我有一个代码正在替换文件并使用特定的字符串(路径)检查文件,我想让它动态 t c#



我想将我的函数从静态方式更改为动态方式,其中这是静态的代码:

string level0path = Application.StartupPath + "/games/Militia/Militia_Data/level0";
string address = "https://test.com/LauncherLogin/Games/MILITIA/Militia_Data/";
HttpWebRequest level0pathR = (HttpWebRequest)WebRequest.Create(address + "level0");
level0pathR.Method = "HEAD";
long level0len;
using (HttpWebResponse resp = (HttpWebResponse)(level0pathR.GetResponse()))
{
level0len = resp.ContentLength / 1024;
}
if (File.Exists(level0path))
{
FileInfo level0Vol = new FileInfo(level0path);
long level0length = 0;
if (level0Vol.Length >= (1 << 10))
{
level0length = level0Vol.Length >> 10;
}
if (level0len > level0length)
{
MessageBox.Show("levl0");
custimizedProgressBar1.Value = 0;
label15.Show();
File.Delete(Application.StartupPath + "/games/Militia/Militia_Data/level0");
Level0Download();
}
else if (level0len < level0length)
{
label15.Show();
File.Delete(Application.StartupPath + "/games/Militia/Militia_Data/level0");
Level0Download();
}
else if (level0len == level0length)
{
// Nothing
}
}

此代码检查主机上的文件和本地磁盘上的文件,并确定是否存在差异。如果文件大小有差异,则下载该文件,否则什么都不会发生。

正如您所看到的,它是用文件位置的变量制作的。

我想让它搜索特定路径中的文件,并使变量和一切自动,使其更小,使代码更小任何帮助

当前您在Militia_Data目录中检查文件级别0的文件大小。我想你也想检查目录中的其他文件吗?然后你需要运行目录文件:

public void test()
{
var militiaData = $"{MediaTypeNames.Application.StartupPath}/games/Militia/Militia_Data/";
var militiaDataDirectoryInfo = new DirectoryInfo(militiaData);
var levelFiles = militiaDataDirectoryInfo.GetFiles("level*",SearchOption.AllDirectories); // get all files that starts with level also from sub folders, if you need all files then *.*
foreach (var levelFile in levelFiles)
{
CheckFile(levelFile.Name);
}
}
private void CheckFile(string levelFile)
{
string level0path = $"{MediaTypeNames.Application.StartupPath}/games/Militia/Militia_Data/{levelFile}";
string address = "https://test.com/LauncherLogin/Games/MILITIA/Militia_Data/";
HttpWebRequest level0pathR = (HttpWebRequest)WebRequest.Create(address + levelFile);
level0pathR.Method = "HEAD";
long level0len;
using (HttpWebResponse resp = (HttpWebResponse)(level0pathR.GetResponse()))
{
level0len = resp.ContentLength / 1024;
}
if (File.Exists(level0path))
{
FileInfo level0Vol = new FileInfo(level0path);
long level0length = 0;
if (level0Vol.Length >= (1 << 10))
{
level0length = level0Vol.Length >> 10;
}
if (level0len > level0length)
{
MessageBox.Show(levelFile);
custimizedProgressBar1.Value = 0;
label15.Show();
File.Delete(level0path);
Level0Download();
}
else if (level0len < level0length)
{
label15.Show();
File.Delete(level0path);
Level0Download();
}
else if (level0len == level0length)
{
// Nothing
}
}
}