gpt4 book ai didi

C# .Net6.0-如何通过C#更改Windows页面文件大小(虚拟内存)?

转载 作者:行者123 更新时间:2023-12-05 02:25:56 27 4
gpt4 key购买 nike

在 Windows 默认设置中,页面文件大小设置为Automatically manage paging file size for all drives

这个项目很特别。它不由运营商维护。这些计算机仅供内部人员处理业务或学习业务流程。这些电脑没有固定的用户,都放在公共(public)区域。出现问题时,值类人员会使用固定的ghost文件重装系统,执行脚本一键优化系统。这些设备比较老,还有一些4G内存64G硬盘的瘦终端。不久之后,新设备将取代它们并拥有新的管理解决方案。作为更换新方案前的临时过渡方案,我认为提供一个简单的“优化”方案将是目前最简单的处理方式。

我想通过 C# .net-6.0 将页面文件大小更改为物理内存的 20% - 50%,如 this (测试计算机的物理内存为 32 GB)

查了一些资料,好像wmic可以满足我的需求。

wmic COMPUTERSYSTEM 设置 AutomaticManagedPagefile=false

wmic PAGEFILESET where name ="C:\\pagefile.sys"set InitialSize=1638,MaximumSize=4095

我在Windows10 2019 LTSC上测试了这两行命令,运行良好。但是当我使用代码执行时,我遇到了一些问题。这是我的代码:

        internal static void ExecuteCmd(string command)
{
try
{
Process process = new();
ProcessStartInfo startInfo = new()
{
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
CreateNoWindow = true,
FileName = "cmd.exe",
Arguments = "/c " + command,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
process.StartInfo = startInfo;
process.Start();
}
catch(Exception e)
{
LogHelper.Error(e.Message);
}
}

internal static void ChangeSystemPageFileSize()
{
string? TotalPhysicalMemory = "0";
string? InitialSize = "0";
string? MaximumSize = "0";

try
{
ManagementObjectSearcher Search = new ManagementObjectSearcher();
Search.Query = new ObjectQuery("Select * From Win32_ComputerSystem");
foreach (ManagementObject obj in Search.Get().Cast<ManagementObject>())
{
TotalPhysicalMemory = $"{Math.Round(Convert.ToDouble(obj["TotalPhysicalMemory"]) / (1024 * 1024))}";

if (!string.IsNullOrWhiteSpace(TotalPhysicalMemory))
{
break;
}
}
InitialSize = Math.Floor(int.Parse(TotalPhysicalMemory) * 0.2).ToString().Trim();
MaximumSize = Math.Floor(int.Parse(TotalPhysicalMemory) * 0.5).ToString().Trim();
CommandHelper.ExecuteCmd("wmic COMPUTERSYSTEM set AutomaticManagedPagefile=false");
CommandHelper.ExecuteCmd("wmic PAGEFILESET where name =\"C:\\\\pagefile.sys\" set InitialSize=" + InitialSize +",MaximumSize=" + MaximumSize);
}
catch (Exception e)
{
LogHelper.Error(e.Message);
}

我获得了正确的物理内存大小,但只有执行的第一个命令生效。当计算机重新启动时,我得到类似this的windows设置。 .

感谢@ProgrammingLlama @user9938我通过 WMI 更新了页面文件大小设置。可能有点问题:

                InitialSize = (UInt32)Math.Floor(TotalPhysicalMemory * 0.2);
MaximumSize = (UInt32)Math.Floor(TotalPhysicalMemory * 0.5);
ManagementObject ComputerSystem = new($@"ROOT\CIMV2:Win32_ComputerSystem.Name='{Environment.MachineName}'");
ComputerSystem["AutomaticManagedPagefile"] = false;
ComputerSystem.Put();
ManagementObject PageFileSetting = new($@"ROOT\CIMV2:Win32_PageFileSetting");
PageFileSetting.SetPropertyValue("Name", "C:\\PAGEFILE.SYS");
PageFileSetting.SetPropertyValue("InitialSize", InitialSize);
PageFileSetting.SetPropertyValue("MaximumSize", MaximumSize);
PageFileSetting["Name"] = "C:\\PAGEFILE.SYS";
PageFileSetting["InitialSize"] = InitialSize;
PageFileSetting["MaximumSize"] = MaximumSize;
PageFileSetting.Put();

SetPropertyValue 方法和Put 方法都不能更新InitialSize MaximumSize Name 的值

也许有人可以给我一些建议?

最佳答案

下面展示了如何使用ManagementObject更改 Windows 页面文件的设置(在操作系统分区上)。

注意:下面的代码进行了有限的测试。建议进行您自己的测试以确保代码按预期运行。虽然代码似乎设置了操作系统驱动器的页面文件大小,但可能有其他(更理想的)方法来设置这些值。此外,在运行以下代码之前,请确保您 Create a System Restore Point .此外,请确保您已对计算机进行了备份。

根据 Win32_ComputerSystem class :

TotalPhysicalMemory

Total size of physical memory. Be aware that, under somecircumstances, this property may not return an accurate value for thephysical memory. For example, it is not accurate if the BIOS is usingsome of the physical memory. For an accurate value, use the Capacityproperty in Win32_PhysicalMemory instead.


下载/安装 NuGet 包:System.Management

添加应用 list 文件:

  • 在 VS 菜单中,单击项目
  • 选择添加新项目...
  • 选择应用程序 list 文件(名称:app.manifest)
  • 点击添加

打开解决方案资源管理器:

  • 在 VS 菜单中,点击查看
  • 选择解决方案资源管理器

修改requestedExecutionLevel:

  • 在解决方案资源管理器中,右键点击 app.manifest 并选择打开

更改自:

<requestedExecutionLevel  level="asInvoker" uiAccess="false" />

更改为:

<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />

PagingFiles 的数据似乎可以通过以下方式修改:

添加以下使用指令

  • 使用 System.Management;
  • 使用 Microsoft.Win32;
  • 使用 System.Diagnostics;

代码:

public UInt64 GetTotalMemoryInMB()
{
UInt64 totalPhysicalMemoryInBytes = 0;

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select Capacity from Win32_PhysicalMemory"))
{
foreach (ManagementObject obj in searcher.Get())
{
if (obj == null)
continue;

totalPhysicalMemoryInBytes += obj["Capacity"] is null ? 0 : Convert.ToUInt64(obj["Capacity"]);
}
}

return totalPhysicalMemoryInBytes / 1024 / 1024;
}

public string SetPageFileWmi(uint initialSizePercentage, uint maximumSizePercentage)
{
StringBuilder sb = new StringBuilder();

//get Windows folder
string? winDir = Environment.GetEnvironmentVariable("windir");

//get drive letter that OS is installed on
string winDriveLetter = winDir?.Substring(0, 2) is null ? String.Empty : winDir.Substring(0, 2); //ex: C:

//get total physical memory
UInt64 totalPhysicalMemory = GetTotalMemoryInMB();

sb.AppendLine($"Total Physical Memory: {totalPhysicalMemory}");

//calculate initial size
UInt32 initialSize = Convert.ToUInt32(Math.Floor(totalPhysicalMemory * (initialSizePercentage / 100.0))); //ex: 20% / 100.0 = 0.2
initialSize = initialSize < 16 ? 16 : initialSize; //initial size needs to be >= 16 MB

//calculate maximum size
UInt32 maximumSize = Convert.ToUInt32(Math.Floor(totalPhysicalMemory * (maximumSizePercentage / 100.0))); //ex: 50% / 100.0 = 0.5

using (ManagementObject obj = new ManagementObject($@"ROOT\CIMV2:Win32_ComputerSystem.Name='{Environment.MachineName}'"))
{
//set value
obj.SetPropertyValue("AutomaticManagedPagefile", false);

//commit
obj.Put(new PutOptions() { Type = PutType.UpdateOnly });
}

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select Name from Win32_PageFile"))
{
foreach (ManagementObject obj in searcher.Get())
{
string? pfName = obj["Name"]?.ToString();

Debug.WriteLine($"pfName: '{pfName}'");

//only get the page file for the OS drive
if (!String.IsNullOrEmpty(pfName) && pfName.ToLower().StartsWith(winDriveLetter.ToLower()))
{
sb.AppendLine($"Name: {pfName}");
sb.AppendLine($"InitialSize: {initialSize}");
sb.AppendLine($"MaximumSize: {maximumSize}");
sb.AppendLine("");

using (ManagementObject obj2 = new ManagementObject($@"ROOT\CIMV2:Win32_PageFileSetting.Name='{pfName}'"))
{
//set value
//obj2.SetPropertyValue("Name", pfName);
obj2.SetPropertyValue("InitialSize", initialSize);
obj2.SetPropertyValue("MaximumSize", maximumSize);

//commit
obj2.Put(new PutOptions() { Type = PutType.UpdateOrCreate });
}
}
}
}

return sb.ToString();
}

用法

string result = SetPageFileWmi(20, 50);

根据 Changing the Location of the Pagefile ,注册表位置是 HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\


更新:

这里有一个重置为默认设置的方法:

public static string SetPageFileDefaultWmi()
{
using (ManagementObject obj = new ManagementObject($@"ROOT\CIMV2:Win32_ComputerSystem.Name='{Environment.MachineName}'"))
{
obj.SetPropertyValue("AutomaticManagedPagefile", true);
obj.Put(new PutOptions() { Type = PutType.UpdateOnly });
}

return "Paging file set to default.";
}

资源:

其他资源:

关于C# .Net6.0-如何通过C#更改Windows页面文件大小(虚拟内存)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74176548/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com