這段時間,公司要我整理一個有點歷史的產品代碼。由于項目歷史久,長期又缺少管理,產品中的項目有點亂,以至于一個DLL模塊配置的輸出路徑竟然有輸出成exe可執行模塊。存在這樣問題的項目有30個左右,而且每個項目要改4個地方,因為有4種生成版本。如果手工去改的話實在很枯燥,但我們是程序員。所以就用代碼了。
1
' 更改所有資源的輸出路徑
2
3
' get folder path
4
scriptName = wscript.scriptfullname
5
scriptPath = Left(scriptName, instrRev(scriptName, "\"))
6
scriptPath = Left(scriptPath, Len(scriptPath) -1)
7
scriptPath = Left(scriptPath, instrRev(scriptPath,"\"))
8
folderPath = scriptPath & "Loc\"
9
10
' create filesystemobject activex object
11
Set fso = CreateObject("Scripting.FileSystemObject")
12
Set fol = fso.GetFolder(folderPath)
13
14
' visit each file which in the folder
15
fileshortName = ""
16
Set fileArr = fol.Files
17
For each fil in fileArr
18
fileName = fil.name
19
If LCase(Right(fileName, 7)) = ".vcproj" Then
20
fileshortName = Left(fileName,Len(fileName) - 7)
21
If LCase(Right(fileshortName, 4)) <> "_enu" Then
22
modifyResource fil.path,status
23
If status =False Then
24
errlist = errlist & fil.Path & vbCr
25
End If
26
End If
27
End If
28
Next
29
30
' Tip when complete the work
31
If Len(errlist) > 0 Then
32
MsgBox errlist & "Can not modify"
33
Else
34
MsgBox "modify successfully"
35
End If
36
37
' modify the resource project setting.
38
Function modifyResource(filePath,status)
39
On Error Resume Next
40
41
resLanguage = UCase(Right(fileshortName, 3))
42
43
' Read Content
44
Set fRead = fso.opentextfile(filePath, 1)
45
fContent = fRead.readAll
46
fRead.close
47
48
' Replace each output file
49
changed = False
50
Set regEx = New RegExp
51
regEx.pattern = "\bOutputFile=.+"
52
regEx.Global = True
53
Set matches = regEx.Execute(fContent)
54
Set childReg = New RegExp
55
For Each match in matches
56
If LCase(Right(match.Value, 9)) <> "\loc.dll""" Then
57
tmpValue = match.Value
58
childReg.pattern = tmpValue
59
If instrRev(tmpValue, "\")>0 Then
60
tmpValue = Left(tmpValue, instrRev(tmpvalue, "\"))
61
ElseIf instrRev(tmpValue,"/") > 0 Then
62
tmpValue = Left(tmpValue,instrRev(tmpValue,"/"))
63
End If
64
tmpValue = tmpValue & resLanguage & "\loc.dll"""
65
childMatches = childReg.Execute(fContent)
66
' fContent = childReg.Replace(fContent, tmpValue)
67
fContent = Replace(fContent, match.Value, tmpValue)
68
changed = True
69
End If
70
Next
71
72
' write back
73
If changed=True Then
74
Set fWrite = fso.opentextfile(filePath, 2, False)
75
fWrite.Write fContent
76
fWrite.close
77
End If
78
' clear error
79
If Not err.number = 0 Then
80
err.clear
81
status = False
82
Else
83
status = True
84
End If
85
End Function
運行結果符合我們的要求。
用ultraEdit打開文件時,會提示是否要轉換成DOS文件格式,但在轉換前用ultraEdit打開不會出現這種問題。問題出在哪兒呢?這還得從DOS文件與非DOS文件格式的區別分析,這兩種文件的差別就是一些控制符不同,如DOS是用\r\n來換行,而Unix是用\n來換行。有了這個分析,就知道問題出在哪了。原因是正則表達式
regEx.pattern = "\bOutputFile=.+"這個表達式把后面的"\r"也匹配進去了,而后來隨著替換字符串時而消失了。所以上面的正則應寫成regEx.pattern = "\bOutputFile=.+"""。改好之后運行,再用ultraEdit打開不會出現這個提示了。