Windows create file without extension

Как создать файл без расширения в Windows 7 и 10

Сегодня рассмотрим, как создать файл без расширения средствами операционных систем Windows без применения сторонних решений, а также при помощи бесплатных приложений, которыми пользуются миллионы людей. В самой ОС не предусмотрена подобная функция, однако это легко обойти, зная несколько секретов.

Командная строка

Универсальный инструмент, посредством которого в Windows можно сделать совершенно всё, главное, знать, каким образом.

  1. Запускаем командную строку любым удобным способом, например, жмём Win + R, а в появившемся окошке выполняем команду «cmd».
  2. В открывшемся окне с черным фоном вводим и выполняем команду «copy con>file» либо «1 >> c:\file», где file – название нашего документа. Можно вводить полный путь к файлу, если пользоваться командной строкой не умеете. Это избавит от необходимости переходить в нужный каталог в текстовом режиме.

Внимания на предупреждения или ошибки не обращаем, свою функцию команда выполнит.

Это самый простой, универсальный и быстрый способ создать пустой файл без расширения в любой версии Windows 7. Все остальные на «Семёрке» и «Десятке» будут незначительно отличаться из-за различий в интерфейсе.

Проводник

Через стандартный менеджер файлов также можно сделать файл без расширения.

  1. Для этого открываем каталог, в котором он должен появиться.
  2. Кликаем правой клавишей мыши на пустом месте в окне и вызываем пункт «Новый».
  3. В выпавшем списке выбираем любой пункт кроме первого.

Появится файл, название которого следует ввести.

  1. Вводим имя нового документа без точек или удаляем точку и жмём «Enter».

  1. Соглашаемся с тем, что после изменения расширения (оно идёт после точки и служит идентификатором для данного типа файлов) документ может стать недоступным.

На этом – всё готово.

Вместо создания нового документа через контекстное меню можно сделать копию любого файла и переименовать его, однако в таком случае документ будет занимать определённое место.Если он не является текстовым, открыть такой объект через блокнот будет невозможно (по крайней мере для нормальной работы с ним).

На многих компьютерах опция редактирования расширения недоступна, исправить это очень просто.

Windows 7

  1. Открываем Проводник, например, при помощи сочетания горячих клавиш Win + E.
  2. Кликаем Alt для вызова главного меню, если оно невидимо.
  3. Из него вызываем пункт «Сервис», в выпавшем списке выбираем «Параметры папок».

  1. Идём во вкладку «Вид».
  2. В фрейме «Дополнительные параметры» пролистываем список пунктов до самого низа и убираем флажок возле опции «Скрывать расширения для…».
  3. Сохраняем новую конфигурацию.

Теперь возможность изменения расширения документов доступна.

Windows 10

В Windows 8 и 10 активация и отключение функции осуществляется проще и быстрее.

  1. В Проводнике вызываем главное меню при помощи Alt, если оно спрятано.
  2. Во вкладке «Вид» отмечаем галочкой опцию «Расширение имён файлов».

Для открытия и изменения содержимого документа его необходимо перетащить в окно любого текстового редактора или через контекстное меню вызвать команду «Открыть с помощью…» и выбрать нужное приложение в выпадающем списке.

Этих способов решения проблемы вполне достаточно для всех случаев, однако мы коснёмся ещё пары вариантов решения задачи для исчерпания темы.

Читайте также:  No pubkey astra linux

Блокнот

Стандартный текстовый редактор Windows не способен помочь в данной ситуации – он автоматически дописывает расширение после названия документа, даже если его не ставить.

Рассмотрим, как создать файл без расширения txt через любой более функциональный аналог Notepad’а. Им может быть AkelPad, Notepad++, Sublime Text и иной подобный текстовый редактор. Рассмотрим на примере последнего, с остальными всё будет точно так же.

  1. Скачиваем приложение с официального сайта, инсталлируем и запускаем его.
  2. Жмём Ctrl + S либо вызываем команду «Сохранить» через пункт главного меню «Файл».
  3. Вводим название документа, в поле «Тип…» указываем «AllFiles (*.*)» и кликаем «Сохранить».

Total Commander

Самый популярный и функциональный файловый менеджер для Windows также позволяет в несколько кликов создать файл без расширения.

  1. Открываем целевой каталог и вызываем контекстное меню папки правым кликом по пустому месту панели.
  2. Выбираем знакомый пункт «Новый» и указываем любой объект, кроме папки и ярлыка.

  1. В окошке для ввода имени пишем любое название без точки и кликаем «ОК» для создания нового объекта.

Также задачу можно решить, переименовав любой файл путём удаления точки из его названия.

Мы рассмотрели основные способы создания файлов без расширения в операционных системах Windows при помощи инструментария самой ОС и посредством популярных приложений.

Getting file names without extensions

When getting file names in a certain folder:

fi.Name gives me a file name with its extension: file1.txt , file2.txt , file3.txt .

How can I get the file names without the extensions? ( file1 , file2 , file3 )

12 Answers 12

Although I am surprised there isn’t a way to get this directly from the FileInfo (or at least I can’t see it).

This solution also prevents the addition of a trailing comma.

I dislike the DirectoryInfo, FileInfo for this scenario.

DirectoryInfo and FileInfo collect more data about the folder and the files than is needed so they take more time and memory than necessary.

This returns the file name only without the extension type. You can also change it so you get both name and the type of file

Use Path.GetFileNameWithoutExtension . Path is in System.IO namespace.

As an additional answer (or to compound on the existing answers) you could write an extension method to accomplish this for you within the DirectoryInfo class. Here is a sample that I wrote fairly quickly that could be embellished to provide directory names or other criteria for modification, etc:

Edit: I also think this method could probably be simplified or awesome-ified if it used LINQ to achieve the construction of the array, but I don’t have the experience in LINQ to do it quickly enough for a sample of this kind.

Edit 2 (almost 4 years later): Here is the LINQ-ified method I would use:

FileInfo knows its own extension, so you could just remove it

or if you’re paranoid that it might appear in the middle, or want to microoptimize:

if file name contains directory and you need to not lose directory:

Just for the record:

This way you don’t use StringBuilder but String.Join() . Also please remark that Path.GetFileNameWithoutExtension() needs a full path ( fi.FullName ), not fi.Name as I saw in one of the other answers.

Below is my code to get a picture to load into a PictureBox and Display a Picture name in to a TextBox without Extension.

Читайте также:  Облачные диски для linux

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

I want to create a .htaccess file manually and discovered it seems impossible through the Windows UI. I get a «you must type a filename.» message. There has to be a way to create files with . as a prefix in Windows.

Can this be done manually?

15 Answers 15

If you start Notepad and then File -> Save As -> Write .htaccess and choose «All Files» as the type — then it will create the .htaccess file for you.

Windows 7, 8 & 10

This is dead easy since Windows 7. In File Explorer, right click anywhere and create a new file. Type the new filename as .something. (notice the appended period) and press enter twice, job done.

So instead of being prompted with

You will instead be prompted with

If you change a file name extension, the file might become unusable.

Note: If you’re having issues then please ensure you have «file name extensions» visible, you can activate this under the «View» menu in File Explorer. Also, this method works for folders too.

Within Notepad select File > Save As.

File name: «.whatever you want» (with the leading dot)

You can do it in Explorer (in Windows 7) by adding a period at the end of the filename:

.whatever you want.

Windows will automatically remove the trailing dot when you validate.

Go to command prompt, cd to the appropriate folder and type:

After confirmation dialog the file will be created and you will be editing it directly. If you just want to create an empty file, try

You could also use Command Prompt with move : move x.extension .extension

You can do this in any program other than Explorer , e.g. Notepad , cmd.exe etc.

You just can’t do it in Explorer, and Raymond Chen has offered an explanation as to why not.

Just type .htaccess. as filename. Notice the dot at the end of htaccess. This will change in Windows to .htaccess without a dot at the end.

Even if you don’t have any third party editor (Notepad++ etc.) then also you can create files with dot as prefix.

To create .htaccess file, first create htaccess.txt file with Context Menu > New Text Document .

Then press Alt + D (Windows 7) and Ctrl + C to copy the path from the Address bar of Windows Explorer.

Then go to command line and type code as below to rename your file:

Now you have a blank .htaccess without opening it in any editor.

How to set the default program for opening files without an extension in Windows?

How to set the default program for opening files without an extension in Windows?

9 Answers 9

With the command line:

Restart the computer for the changes to take effect.

To give credit, I learned this from the vim wikia here and here

Instead of «C:\path\to\. » , the following macros may be useful:

  • %SystemDrive% — drive windows is installed on, i.e. C:\
  • %ProgramFiles% — e.g. «C:\Program Files\»
  • %ProgramFiles(x86)% — e.g. «C:\Program Files (x86)\»
Читайте также:  Лучший почтовый клиент для windows 2020

You will need to properly escape them though:

To set the icon to be the same as .txt files (I didn’t do this, since it automatically made the files’ icons display as Notepad++ files):

To undo, you can read the assoc /? or ftype /? information, e.g.:

Normal files with an extension can have a program associated however this is not the case with files that don’t have an extension. If you double click on one and select an application and check the box to always use that application it is ignored and every time you select a file you have to choose the application.

You can force this using the registry:

  • Start the registry editor (regedit.exe)
  • Move to HKEY_CLASSES_ROOT
  • From the Edit menu select New — Key
  • Enter a name of ‘.’ and press Enter (don’t type the quotes)
  • Select the new ‘.’ key
  • Double click the (Default) value
  • Change to the HKEY_CLASSES_ROOT used to open, e.g. NOTEPAD for the notepad.exe application NOTEPAD
  • Click OK

If you now double click on a file with no extension it will open with the application selected.

To check what an existing application used look at its entry under HKEY_CLASSES_ROOT, e.g. HKEY_CLASSES_ROOT.doc uses Word.Document.8 so if you wanted this as your default editor you would change HKEY_CLASSES_ROOT.(Default) to Word.Document.8.

Any method which avoids the need to edit the registry is as follows:

how to run an executable file without EXE extension using CMD script?

The situation is that I have a portable application that needs to have set environment variable. Other way it tries to set it’s settings in user program data dir.

To avoid running the executable in non-portable mode (to avoid allowing it to run without any parameters) I erased the file’s «.exe» extension, but then I cannot run it not only by mouse (which I want) but also through start command.

Is there any way to run such executable file that has no exe extension ?

3 Answers 3

Yes – simply entering the program’s full filename usually works. (The .exe requirement only exists in the GUI shell.)

(It might be that the file needs an extension, though – so if you can’t get MyProgram to run, rename it to MyProgram.notexe or MyProgram.lol and try again.)

Any file with any extension and first two bytes MZ will be treated like an EXE.

  1. Create a new a.txt file,
  2. Type in it MZ , save it.
  3. Open cmd , go to its folder,
  4. Type a.txt and see the error message.

Replace MZ with MS and try again — this time notepad will run with file opened.

I tried to run process from file without the .exe extension. When I failed to do so from cmd.exe I give a try some powershell commands. Here is one:

The documentation says about Default syntax and UseShellExecute. With just:

the command uses UseShellExecute syntax and returns error about not associated application to that file type. To force the Default syntax I added parameter that the UseShellExecute doesn’t have:

My program was started and wrote output to the console. This was enough for me, because I needed it only for test purpose.

Оцените статью