Это может быть немного прочитано, так что заранее извините. И это мой испытанный и проверенный способ сделать это, может быть более простой способ, но это от меня, когда я бросаю код в стену и смотрю, что застряло
Код TL; DR для этого вопроса, в частности
Хорошо, извините, Это на самом деле не проверено. этот В ТЕОРИИ работает
public static void ChangeMe()
{
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string path1 = docPath + "\\Test.txt";
string path2 = docPath + "\\Test.bat";
string[] lines =
{
"select disk 0",
"clean",
"convert gpt",
"create partition primary size=300",
"format quick fs=ntfs label=Windows RE tools",
"assign letter=T"
};
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.txt")))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
string[] lines =
{
"diskpart /s test.txt"
};
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
System.Diagnostics.Process.Start(path2);
}
Если то, что вы хотите сделать, можно сделать в пакетном файле, возможно, более сложная работа - заставить С # написать файл .bat и запустить его. Если вам нужен пользовательский ввод, вы можете поместить его в переменную и записать его в файл в C #. для этого потребуется метод проб и ошибок, потому что это все равно, что управлять марионеткой с помощью другой марионетки. А с Diskpart это немного сложнее, потому что вам нужно создать 2 файла: один - это .bat, а другой - текстовый.
вот пример только командного файла. В этом случае функция предназначена для кнопки в приложении форума Windows, которая очищает очередь печати.
using System.IO;
using System;
public static void ClearPrintQueue()
{
//this is the path the document or in our case batch file will be placed
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//this is the path process.start usues
string path1 = docPath + "\\Test.bat";
// these are the batch commands
// remember its "", the comma separates the lines
string[] lines =
{
"@echo off",
"net stop spooler",
"del %systemroot%\\System32\\spool\\Printers\\* /Q",
"net start spooler",
//this deletes the file
"del \"%~f0\"" //do not put a comma on the last line
};
//this writes the string to the file
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
{
//This writes the file line by line
foreach (string line in lines)
outputFile.WriteLine(line);
}
System.Diagnostics.Process.Start(path1);
}
ЕСЛИ вам нужен ввод пользователя, вы можете попробовать что-то вроде этого.
Это сделано для того, чтобы установить статический IP-адрес компьютера, но спросить пользователя, какой IP, шлюз и DNS-сервер.
вам понадобится это для работы
public static void SetIPStatic()
{
//These open pop up boxes which ask for user input
string STATIC = Microsoft.VisualBasic.Interaction.InputBox("Whats the static IP?", "", "", 100, 100);
string SUBNET = Microsoft.VisualBasic.Interaction.InputBox("Whats the Subnet?(Press enter for default)", "255.255.255.0", "", 100, 100);
string DEFAULTGATEWAY = Microsoft.VisualBasic.Interaction.InputBox("Whats the Default gateway?", "", "", 100, 100);
string DNS = Microsoft.VisualBasic.Interaction.InputBox("Whats the DNS server IP?(Input required, 8.8.4.4 has already been set as secondary)", "", "", 100, 100);
//this is the path the document or in our case batch file will be placed
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//this is the path process.start usues
string path1 = docPath + "\\Test.bat";
// these are the batch commands
// remember its "", the comma separates the lines
string[] lines =
{
"SETLOCAL EnableDelayedExpansion",
"SET adapterName=",
"FOR /F \"tokens=* delims=:\" %%a IN ('IPCONFIG ^| FIND /I \"ETHERNET ADAPTER\"') DO (",
"SET adapterName=%%a",
"REM Removes \"Ethernet adapter\" from the front of the adapter name",
"SET adapterName=!adapterName:~17!",
"REM Removes the colon from the end of the adapter name",
"SET adapterName=!adapterName:~0,-1!",
//the variables that were set before are used here
"netsh interface ipv4 set address name=\"!adapterName!\" static " + STATIC + " " + STATIC + " " + DEFAULTGATEWAY,
"netsh interface ipv4 set dns name=\"!adapterName!\" static " + DNS + " primary",
"netsh interface ipv4 add dns name=\"!adapterName!\" 8.8.4.4 index=2",
")",
"ipconfig /flushdns",
"ipconfig /registerdns",
":EOF",
"DEL \"%~f0\"",
""
};
//this writes the string to the file
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
{
//This writes the file line by line
foreach (string line in lines)
outputFile.WriteLine(line);
}
System.Diagnostics.Process.Start(path1);
}
Как я сказал. Это может быть немного сложно, но никогда не выходит из строя, если я не напишу пакетные команды неправильно.
Это код для diskpart. Вы должны понимать командную строку, чтобы заставить их работать. С diskpart вы не можете просто написать сценарий вроде
diskpart
select disk 0
clean
convert gpt
create partition primary size=300
format quick fs=ntfs label=Windows RE tools
assign letter=T
Это связано с тем, что diskpart открывает собственное окно, а остальные команды просто вызывают ошибки в окне командной строки, поэтому вам нужно получить C #, чтобы сначала записать текстовый файл с командами. Затем командный файл с командой diskpart для вызова только что написанного текстового файла.
Как я сказал вначале, этот на самом деле не тестировался. этот В ТЕОРИИ работает
public static void ChangeMe()
{
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string path1 = docPath + "\\Test.txt";
string path2 = docPath + "\\Test.bat";
string[] lines =
{
"select disk 0",
"clean",
"convert gpt",
"create partition primary size=300",
"format quick fs=ntfs label=Windows RE tools",
"assign letter=T"
};
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.txt")))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
string[] lines =
{
"diskpart /s test.txt"
};
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
System.Diagnostics.Process.Start(path2);
}
person
Leo song
schedule
09.12.2020