修改文件及目录的名称
(
十
)
本文讲述,修改文件夹和文件的名称。
1.
添加一个按钮“
…
”用来浏览要修改的文件夹,一个文本框控件来显示名称:
IDC_EDPATHNAME
,按钮代码如下:
BROWSEINFO
bi
;
char
buffer
[
MAX_PATH
];
ZeroMemory
(
buffer
,
MAX_PATH
);
bi
.
hwndOwner
=
GetSafeHwnd
();
bi
.
pidlRoot
=
NULL
;
bi
.
pszDisplayName
=
buffer
;
bi
.
lpszTitle
=
"
选择一个文件夹
"
;
bi
.
ulFlags
=
BIF_EDITBOX
;
bi
.
lpfn
=
NULL
;
bi
.
lParam
=0;
bi
.
iImage
=0;
LPITEMIDLIST
pList
=
NULL
;
if
((
pList
=
SHBrowseForFolder
(&
bi
))!=
NULL
)
{
char
path
[
MAX_PATH
];
ZeroMemory
(
path
,
MAX_PATH
);
SHGetPathFromIDList
(
pList
,
path
);
pathofpath
=
strpathname
=
path
;
CString
pathname
,
temp
;
pathname
=
path
;
int
pos
=
pathname
.
Find
(
"//"
);
while
(
pos
>0)
{
//temp=pathname;
pathname
=
pathname
.
Right
(
pathname
.
GetLength
()-1-
pos
);
pos
=
pathname
.
Find
(
"//"
);
}
GetDlgItem
(
IDC_EDPATHNAME
)->
SetWindowText
(
pathname
);
pathofpath
=
pathofpath
.
Left
(
pathofpath
.
GetLength
()-
pathname
.
GetLength
());
}
2.
添加一个文本框控件:
IDC_EDPATHNAMESET
,用来接收新文件夹名称,一个按钮“修改”,代码如下:
if
(
strpathname
.
IsEmpty
())
return
;
CString
edpathname
;
GetDlgItem
(
IDC_EDPATHNAMESET
)->
GetWindowText
(
edpathname
);
if
(
edpathname
.
IsEmpty
())
return
;
pathofpath
+=
edpathname
;
if
(::
MoveFile
(
strpathname
,
pathofpath
))
AfxMessageBox
(
"
修改成功
"
);
3.
添加一个按钮“
…
”用来浏览要修改的文件,一个文本框控件来显示名称:
IDC_EDNAME
,按钮代码如下:
CFileDialog
log
(
TRUE
,
"
文件
"
,
"*.*"
,
OFN_HIDEREADONLY
|
OFN_ALLOWMULTISELECT
,
"FILE(*.*)|*.*||"
,
NULL
);
if
(
log
.
DoModal
()==
IDOK
)
{
strfilename
=
log
.
GetPathName
();
CString
filename
=
log
.
GetFileName
();
GetDlgItem
(
IDC_EDNAME
)->
SetWindowText
(
filename
);
}
4.
添加一个文本框控件:
IDC_EDNAMESET
,用来接收新文件夹名称,一个按钮“修改”,代码如下:
if
(
strfilename
.
IsEmpty
())
return
;
CString
stredfilename
;
GetDlgItem
(
IDC_EDNAMESET
)->
GetWindowText
(
stredfilename
);
if
(
stredfilename
.
IsEmpty
())
return
;
CString
temp
,
strtemp
;
strtemp
=
temp
=
strfilename
;
int
pos
=
temp
.
Find
(
"//"
);
while
(
pos
>0)
{
temp
=
temp
.
Right
(
temp
.
GetLength
()-1-
pos
);
pos
=
temp
.
Find
(
"//"
);
}
strtemp
=
strtemp
.
Left
(
strtemp
.
GetLength
()-
temp
.
GetLength
());
strtemp
+=
stredfilename
;
CFile
::
Rename
(
strfilename
,
strtemp
);
AfxMessageBox
(
"
修改成功
"
);
其中有
3
个变量的声明:
CString
strpathname
;
CString
strfilename
;
CString
pathofpath
;
完成。