Click here to Skip to main content
15,891,926 members
Articles / Programming Languages / C++

Change File Extension Context Menu

Rate me:
Please Sign up or sign in to vote.
4.63/5 (15 votes)
7 May 2008CPOL5 min read 83.7K   918   29  
An easy and flexible way to change file extensions.
#include "stdafx.h"
#include "NewextDlg.h"
#include "Extmanager.h"

//
C_extmanager::C_extmanager()
{
	menubitmap.LoadBitmapW(MAKEINTRESOURCE(IDB_MENUBITMAP));
	if (menubitmap.IsNull()) throw EXTM_RES_ERROR;

	filecount=0;
	firstFileext.Empty();
	ctxFileext.Empty();

	v_fileList.clear();

}
//
C_extmanager::~C_extmanager()
{
	v_fileList.clear();
}
//
void C_extmanager::addFile(TCHAR *afl)
{
	CString fe;
	fe=afl;
	v_fileList.push_back(fe);//build file list

	filecount+=1;
	getfirstExt(afl);
}
//
void C_extmanager::getfirstExt(TCHAR *xtn)
{
	if (filecount==1)//just for first file	//filecount+=1; must be called before this
	{
	splitter.Split(xtn);//split path for ext	//check for empty ext!!!
	ctxFileext=firstFileext=splitter.ext_nodot;
	ctxFileext.MakeUpper();
	}
}
//
void C_extmanager::processFiles()
{
	nextdlg.newext=firstFileext;
}
//
void C_extmanager::changeExtensions()
{
	if (nextdlg.DoModal()!=IDOK) return;

	//now change extensions
	if (filecount>0)
	{
		for ( v_fileListiter=v_fileList.begin(); v_fileListiter<v_fileList.end(); v_fileListiter++)
		{if (!changeExt(*v_fileListiter, nextdlg.newext)) break;}
	}
}
//
bool C_extmanager::changeExt(CString &fname,CString &newext)
{
try {
	splitter.Split(fname);
	splitter.ext_nodot.MakeLower();

	CString toname=newext;//reusing toname
	toname.MakeLower();

	if (splitter.ext_nodot==toname) return true;//case-insensitive compare

	toname.Empty();//reusing toname

	SHFILEOPSTRUCT lpFileOp;
	memset(&lpFileOp,0,sizeof(lpFileOp));

	lpFileOp.hwnd=NULL;
	lpFileOp.fFlags=FOF_ALLOWUNDO;
	lpFileOp.wFunc=FO_RENAME;

	fname+='\0';//add buffer-terminating null to old name
	lpFileOp.pFrom=fname;

	toname=splitter.drive+splitter.dir+splitter.filename+_T(".")+newext;
	lpFileOp.pTo=toname;
	
	if (0!=SHFileOperation(&lpFileOp)) {/*MSGBOX0("SHFileOperation failed");*/return false;}
} catch (...) {return false;}
return true;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Croatia Croatia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions