Блог → Программирование

Использование 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);
    }
}

Улучшения следующие:

Сначала идет код для командного интерпретатора Windows, а затем — код на C#. При запуске скрипт компилирует сам себя: cmd.exe выполняет код сверху, а компилятор C# видит этот код как комментарий. Поддерживается .NET Framework версий от 2.0 до 4.5. Последней версии в коде не указано, но так как 4.5 устанавливается в папку 4.0, всё работает.

Осталось теперь придумать зачем это надо. C# — не скриптовый язык, поэтому без IDE с автодополнением и подсказками очень неудобно.

28 декабря 2012 22:35 

Комментарии


qertis
qertis — 13 лет назад blog.baskovsky.ru
Спасибо!
Очень удобный подход для создания автоматизированных скриптов (реорганизация директорий или массовое переименование файлов). А главное, удобно написав в VS, поделиться с другом по почте. И запуская, не требовать права подтверждения администратора!

DuMOHsmol
DuMOHsmol — 13 лет назад anothersite.ru
Рад помочь :)
Очень удобный подход для создания автоматизированных скриптов (реорганизация директорий или массовое переименование файлов).
Есть же Powershell для этого. Хотя, честно говоря, я бы и сам быстрее на C# написал.

https://U7Bm8.Mssg.me/
https://U7Bm8.Mssg.me/ — 2 недели назад
I was recommended this web site by my cousin. I aam not
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/

https://predictedlineup3.Wordpress.com/
https://predictedlineup3.Wordpress.com/ — 1 неделю назад
Asking questions are realy good thing if you aree not understanding anything entirely, however this
post provides fastidious understanding yet. https://predictedlineup3.Wordpress.com/

https://Ukcarers.co.uk/employer/tonebet-casino/
https://Ukcarers.co.uk/employer/tonebet-casino/ — 1 неделю назад
I'm curious to find out what blog platform you happen to be using?
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/

https://Mark-Strategies.Blogspot.com/2025/08/online-marketing-strategies.html
https://Mark-Strategies.Blogspot.com/2025/08/online-marketing-strategies.html — 6 дней назад
Whaat i do not realize is in truth how you aare now not really a
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

https://Telegra.ph/Casino-Bonuses-And-Free-Spins-09-02
https://Telegra.ph/Casino-Bonuses-And-Free-Spins-09-02 — 11 часов назад
Heeya i'm for thee first tiime here. I found this board and I
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

https://Justpaste.it/azurslottrustedcasino
https://Justpaste.it/azurslottrustedcasino — 11 часов назад
Woah! I'm really enjoying the template/theme of this blog.
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

https://zenwriting.net/fou9plvhra
https://zenwriting.net/fou9plvhra — 11 часов назад
This website was... how do yyou say it? Relevant!! Finally I ave found something which helped me.
Thanks! https://zenwriting.net/fou9plvhra

https://Sites.Google.com/view/fun-with-real-money-games/fun-with-real-money-games
https://Sites.Google.com/view/fun-with-real-money-games/fun-with-real-money-games — 10 часов назад
Hi would you mind letting me know which webhost you're working
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

https://Azurslot.Jimdofree.com/
https://Azurslot.Jimdofree.com/ — 10 часов назад
Definjtely consider that that you stated. Your favourite reason appeared to be at thhe web the simplest thing to remember of.
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/

https://Writeablog.net/5xa1u0vfdh
https://Writeablog.net/5xa1u0vfdh — 10 часов назад
Hello colleagues, how is all, and what you wish for to sayy regarding this post, in my view its truly remarkable in support of me. https://Writeablog.net/5xa1u0vfdh

https://sites.Google.com/view/azurslotnewslotgames/azurslot-new-slot-games
https://sites.Google.com/view/azurslotnewslotgames/azurslot-new-slot-games — 10 часов назад
We stumbled ovcer here coming from a different website
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

https://zenwriting.net/4enc6hyz2j
https://zenwriting.net/4enc6hyz2j — 10 часов назад
Its like you read my mind! You appear to understand a
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

https://Zenwriting.net/c9iadqodtw
https://Zenwriting.net/c9iadqodtw — 10 часов назад
Hi, this weekend is pleasant in favor of me, since this time
i am reading this fantastic educational article here at my residence. https://Zenwriting.net/c9iadqodtw

https://Penzu.com/public/8228a2acbfbcc129
https://Penzu.com/public/8228a2acbfbcc129 — 10 часов назад
Definitely believe that which yyou said. Your favorite reason sesmed to be on the net thhe simplest thing to be aware
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

Ваше имя Сайт или блог (опционально) Аватар (опционально, e-mail для Gravatar или ссылка на картинку с ipic.su) Текст комментария

Справка по написанию комментария

  • Для вставки аватара зарегиструйтесь на сервисе Gravatar и укажите ваш e-mail. Вы также можете загрузить аватар на http://ipic.su и скопировать текст с поля «прямая ссылка». Другие сервисы или хостинги изображений не поддерживаются. Большие изображения будут уменьшены автоматически. Пример:

    http://ipic.su/img/img7/fs/user4.1358962896.png
  • Имя, адрес и аватар сохраняются, второй раз вводить не придётся
  • Кликните на аватар, чтобы вставить имя пользователя
  • Слово обрамлённое «звёздочками» становится *жирным*
  • Адрес ссылки автоматически становится ссылкой — http://anothersite.ru
  • Ссылки на текст с http://pastebin.com автоматически разворачиваются в тексте комментария
  • Цитату следует начинать со знака «больше»:
    > пример многострочной
    > цитаты