重命名文件目录
(
七
)
本文讲述如何对目录进行重命名。
1.
创建一个对话框工程:
RenameFolder
。
2.
声明变量:
CString
oName
,
name
;
3.
添加一个按钮“浏览”,代码如下:
CString
ReturnPath
;
TCHAR
szPath
[
_MAX_PATH
];
BROWSEINFO
bi
;
bi
.
hwndOwner
=
NULL
;
bi
.
pidlRoot
=
NULL
;
bi
.
lpszTitle
=
_T
(
"
请选择一个文件夹
"
);
bi
.
pszDisplayName
=
szPath
;
bi
.
ulFlags
=
BIF_RETURNONLYFSDIRS
;
bi
.
lpfn
=
NULL
;
bi
.
lParam
=
NULL
;
LPITEMIDLIST
pItemIDList
=
SHBrowseForFolder
(&
bi
);
if
(
pItemIDList
)
{
oName
=
szPath
;
if
(
SHGetPathFromIDList
(
pItemIDList
,
szPath
))
ReturnPath
=
szPath
;
}
else
ReturnPath
=
""
;
m_Path
.
SetWindowText
(
ReturnPath
);
其中:
m_Path
是显示选择目录的文本框变量。
4.
添加一个函数删除文件目录同时进行拷贝到新目录,如下:
void
CRenameFolderDlg
::
DelFolder
(
CString
path
)
{
CFileFind
file
;
if
(
path
.
Right
(1) !=
"//"
)
{
path
+=
"//*.*"
;
}
BOOL
bf
;
bf
=
file
.
FindFile
(
path
);
while
(
bf
)
{
bf
=
file
.
FindNextFile
();
//
是文件时直接删除
if
(!
file
.
IsDots
() && !
file
.
IsDirectory
())
{
CString
path1
;
path1
=
file
.
GetFilePath
();
path1
.
Replace
(
oName
,
name
);
CopyFile
(
file
.
GetFilePath
(),
path1
,
true
);
DeleteFile
(
file
.
GetFilePath
());
}
else
if
(
file
.
IsDots
())
continue
;
else
if
(
file
.
IsDirectory
())
{
CString
path2
;
path
=
file
.
GetFilePath
();
path2
=
file
.
GetFilePath
();
//
是目录时
,
继续递归调用函数删除该目录下的文件
path2
.
Replace
(
oName
,
name
);
CreateDirectory
(
path2
,
NULL
);
DelFolder
(
path
);
//
目录为空后删除目录
RemoveDirectory
(
path
);
}
}
}
5
.添加一个按钮“重命名”,代码如下:
CString
str
,
strn
;
m_Path
.
GetWindowText
(
str
);
m_NewName
.
GetWindowText
(
name
);
strn
=
str
;
strn
.
Replace
(
oName
,
name
);
CreateDirectory
(
strn
,
NULL
);
DelFolder
(
str
);
RemoveDirectory
(
str
);
即可实现对文件目录的重命名。