Использование C# в bat файле
На «Хабрахабре» выкладывали статью о создании *.bat файлов, выполняющих код на C#. К сожалению, ту статью почему-то удалили, но сам код у меня остался. Ниже его доработанная и исправленная версия:
/* @echo off && cls && echo Loading... && echo. set WinDirNet=%WinDir%\Microsoft.NET\Framework if exist "%WinDirNet%\v2.0.50727\csc.exe" set csc="%WinDirNet%\v2.0.50727\csc.exe" if exist "%WinDirNet%\v3.5\csc.exe" set csc="%WinDirNet%\v3.5\csc.exe" if exist "%WinDirNet%\v4.0.30319\csc.exe" set csc="%WinDirNet%\v4.0.30319\csc.exe" if "%csc%" == "" ( echo .NET Framework not found! && echo. && pause && exit ) %csc% /nologo /out:"%~dpnx0.exe" "%~dpnx0" if not "%ERRORLEVEL%" == "0" ( echo. && pause && exit ) cls "%~dpnx0.exe" %* del "%~dpnx0.exe" exit */ using System; class HelloWorld { static void Main(string[] args) { Console.ForegroundColor = System.ConsoleColor.Cyan; Console.Title = "Test application"; Console.WriteLine("Hello, World!\r\nI am at " + System.Environment.Version); int i = 0; foreach (string item in args) { Console.WriteLine(i+": "+item); i++; } Console.ReadKey(true); } }
Улучшения следующие:
- Сообщение о загрузке программы
- В случае ошибки компиляции cmd.exe не закрывается и показывает текст ошибки
- Программе можно передавать параметры
- Скрипт корректно запускается как при клике, так и вызове из командной строки, ярлыка и т.д.
Сначала идет код для командного интерпретатора Windows, а затем — код на C#. При запуске скрипт компилирует сам себя: cmd.exe выполняет код сверху, а компилятор C# видит этот код как комментарий. Поддерживается .NET Framework версий от 2.0 до 4.5. Последней версии в коде не указано, но так как 4.5 устанавливается в папку 4.0, всё работает.
Осталось теперь придумать зачем это надо. C# — не скриптовый язык, поэтому без IDE с автодополнением и подсказками очень неудобно.
Комментарии
Очень удобный подход для создания автоматизированных скриптов (реорганизация директорий или массовое переименование файлов). А главное, удобно написав в VS, поделиться с другом по почте. И запуская, не требовать права подтверждения администратора!
certain whether this ppst is written by way of him as no one else understand
such certain approximately my problem. You are amazing!
Thanks! https://U7Bm8.Mssg.me/
post provides fastidious understanding yet. https://predictedlineup3.Wordpress.com/
I'm experiencing some small security issues with my latest
blog and I would like to find something more safeguarded.
Do you have any recommendations? https://Ukcarers.co.uk/employe...tonebet-casino/
lot more neatly-appreciated than you might be now. You're
so intelligent. Yoou understand thus considerably on the
subjectt of this subject,produced me in my opinion consider it from numerous numerous angles.
Its likke women and men aren't involved except it is something to accomplish with Woman gaga!
Your personal stuffs great. Always maintain it up! https://Mark-Strategies.Blogsp...strategies.html
find It really useful & it helped me out a lot.
I hope too give something back and aid others like you helped
me. https://Telegra.ph/Casino-Bonu...ree-Spins-09-02
It's simple, yeet effective. A lot of times it's difficult to
get that "perfect balance" between user friendliness and visual appearance.
I must say that you've donme a excellent job with this.
In addition, the blog loads very quick for me on Firefox.
Outstanding Blog! https://Justpaste.it/azurslottrustedcasino
Thanks! https://zenwriting.net/fou9plvhra
with? I've loaded your blog inn 3 completely different web browsers annd I must
say this blogg loads a lot quicker then most. Can you recommend a good web hosting
provider at a honest price? Thank you, I apprecite it! https://Sites.Google.com/view/...eal-money-games
I say to you, I certainly get irked eve as people
think about concerns that they just do not recognise about.
Youu managed to hit the nail upon the ttop and outlined out
the entire thing with no need side-effects , other people
could take a signal. Will likely be avain to get more. Thanks https://Azurslot.Jimdofree.com/
and thought I mmay as well check things out. I like
what I see so now i'm following you. Look forward tto looking into
your web pagee again. https://sites.Google.com/view/...-new-slot-games
lot approximately this, such aas you wrote the guide
in iit or something. I think that you could do
with a few percent to drige the message home a
bit, however instead of that, this is great blog.
An excellent read. I will definitely be back. https://zenwriting.net/4enc6hyz2j
i am reading this fantastic educational article here at my residence. https://Zenwriting.net/c9iadqodtw
of. I say to you, Icertainly get irked while people think about worries
that they plainly do not know about. You managed to hit the
nail uplon the top aas well as defined out the whole thing without hhaving side-effects , people could take a
signal. Will probably be back to get more. Thanks https://Penzu.com/public/8228a2acbfbcc129