# .NET for MaxScript - 集成指南
从PDF转换为优化Markdown格式
本文档介绍了如何在3ds Max的MaxScript中使用.NET框架进行集成开发,包含各种UI控件、文件操作和数据处理示例。
-- 创建测试对话框
try DestroyDialog Testing catch ()
rollout Testing "测试" width:30 height:20
(
dotNetControl Butt "Button" width:100 height:50
on Butt DragOver e do
(
kk = e.data
yy = kk.GetFileDropList()
Testing.Butt.Text = yy.item[0]
)
)
FloatTest = newRolloutFloater "模板" 200 200
addRollout Testing FloatTest
Testing.Butt.allowdrop = true
rollout test "Test"
(
dotNetControl tb "system.windows.forms.textBox" height:80
on test open do
(
tb.multiLine = true
sb = dotNetClass "System.Windows.Forms.ScrollBars"
tb.scrollBars = sb.vertical
tb.acceptsReturn = true
tb.acceptsTab = true
tb.wordWrap = true
tb.focus()
)
)
createDialog test
功能说明:
-- 创建文本框
hTextBox = dotNetObject "System.Windows.Forms.TextBox"
hTextBox.Location = dotNetObject "System.Drawing.Point" 10 10
hTextBox.Width = 280
hTextBox.Height = 280
hTextBox.Visible = true
hTextBox.MultiLine = true
ScrollBars = dotNetClass "System.Windows.Forms.ScrollBars"
hTextBox.ScrollBars = ScrollBars.Vertical
hTextBox.AcceptsReturn = true
hTextBox.AcceptsTab = true
hTextBox.WordWrap = true
-- 创建窗体
hForm = dotNetObject "System.Windows.Forms.Form"
hForm.Size = dotNetObject "System.Drawing.Size" 310 335
hForm.Text = ".Net 2.0 Form with TextBox"
hForm.Controls.Add(hTextBox)
hForm.TopMost = true
FormBorderStyle = dotNetClass "System.Windows.Forms.FormBorderStyle"
hForm.FormBorderStyle = FormBorderStyle.FixedDialog
hForm.ShowInTaskbar = false
hForm.MinimizeBox = false
hForm.MaximizeBox = false
-- 设置窗体背景色
maxBackColor = colorMan.getColor #background
Color = dotNetClass "System.Drawing.Color"
hForm.BackColor = Color.FromArgb (maxBackColor[1] * 255.0f) (maxBackColor[2] * 255.0f) (maxBackColor[3] * 255.0f)
-- 显示窗体
hApp = dotNetClass "System.Windows.Forms.Application"
hApp.Run hForm
/*
System.Windows.Forms.MessageBoxButtons (枚举)
- AbortRetryIgnore
- OK
- OKCancel
- RetryCancel
- YesNo
- YesNoCancel
System.Windows.Forms.MessageBoxDefaultButton (枚举)
- Button1
- Button2
- Button3
System.Windows.Forms.MessageBoxIcon (枚举)
- Asterisk
- Error
- Exclamation
- Hand
- Information
- None
- Question
- Stop
- Warning
MessageBox.show (方法)
MessageBox.show(text, caption, buttons, icon, defaultButton)
*/
(
-- 设置.NET类/对象
local mb = dotNetClass "System.Windows.Forms.MessageBox"
local buttons = dotNetClass "System.Windows.Forms.MessageBoxButtons"
local icons = dotNetClass "System.Windows.Forms.MessageBoxIcon"
local defaultButton = dotNetClass "System.Windows.Forms.MessageBoxDefaultButton"
local dialogResult = dotNetClass "System.Windows.Forms.DialogResult"
-- 显示消息框
local result = mb.show "Do you want to save before quitting?" "Quit" buttons.YesNoCancel icons.Information defaultButton.Button3
-- 评估用户点击的按钮
if (result == dialogResult.Yes) then (
format "YES"
) else if (result == dialogResult.No) then (
format "NO"
) else if (result == dialogResult.Cancel) then (
format "CANCEL"
)
)
(
Color = dotNetClass "System.Drawing.Color"
ScrollBars = dotNetClass "System.Windows.Forms.ScrollBars"
-- 创建选项卡容器
tabControl1 = dotnetobject "system.windows.forms.TabControl"
tabControl1.size = dotnetobject "system.drawing.size" 395 195
tabControl1.Location = dotnetobject "System.Drawing.Point" 0 0
-- 创建选项卡页面
tabPage1 = dotnetobject "System.Windows.Forms.TabPage"
tabPage1.text = "Goodbye World"
tabPage2 = dotnetobject "System.Windows.Forms.TabPage"
tabPage2.text = "Hello World"
tabPage1.backColor = color.fromArgb 200 200 200
tabPage2.backColor = color.fromArgb 200 200 200
-- 创建数据网格
DGrid1 = dotnetobject "System.Windows.Forms.DataGrid"
DGrid1.Location = dotNetObject "System.Drawing.Point" 10 10
DGrid1.Width = 365
DGrid1.Height = 120
DGrid1.Visible = true
-- 创建文本框
TB1TextBox = dotNetObject "System.Windows.Forms.TextBox"
TB1TextBox.Location = dotNetObject "System.Drawing.Point" 10 10
TB1TextBox.Width = 365
TB1TextBox.Height = 120
TB1TextBox.Visible = true
TB1TextBox.MultiLine = true
TB1TextBox.ScrollBars = ScrollBars.Vertical
TB1TextBox.AcceptsReturn = true
TB1TextBox.AcceptsTab = true
TB1TextBox.WordWrap = true
-- 创建按钮
button01 = dotnetobject "System.Windows.Forms.button"
button01.text = "goodbye"
button01.Location = dotNetObject "System.Drawing.Point" 300 138
-- 创建窗体
TabForm = dotNetObject "System.Windows.Forms.Form"
TabForm.Size = dotNetObject "System.Drawing.Size" 400 225
TabForm.Text = "Title"
TabForm.TopMost = true
FormBorderStyle = dotNetClass "System.Windows.Forms.FormBorderStyle"
TabForm.FormBorderStyle = FormBorderStyle.FixedDialog
TabForm.ShowInTaskbar = false
TabForm.MinimizeBox = true
TabForm.MaximizeBox = false
Tabform.helpbutton = true
-- 添加UI元素到选项卡
tabpage1.controls.add(TB1textbox)
tabpage1.controls.add(button01)
tabpage2.controls.add(DGrid1)
-- 添加选项卡到容器
tabcontrol1.controls.add(tabpage1)
tabcontrol1.controls.add(tabpage2)
-- 添加选项卡容器到窗体
TabForm.Controls.Add(tabcontrol1)
-- 显示应用程序窗体
TTApp = dotNetClass "System.Windows.Forms.Application"
TTApp.Run TabForm
)
(
dotnet.loadassembly "System.Data"
Color = dotNetClass "System.Drawing.Color"
ScrollBars = dotNetClass "System.Windows.Forms.ScrollBars"
-- 创建选项卡容器
tabControl1 = dotnetobject "system.windows.forms.TabControl"
tabControl1.size = dotnetobject "system.drawing.size" 395 195
tabControl1.Location = dotnetobject "System.Drawing.Point" 0 0
-- 创建选项卡页面
tabPage1 = dotnetobject "System.Windows.Forms.TabPage"
tabPage1.text = "Goodbye World"
tabPage2 = dotnetobject "System.Windows.Forms.TabPage"
tabPage2.text = "Hello World"
tabPage1.backColor = color.fromArgb 200 200 200
tabPage2.backColor = color.fromArgb 200 200 200
-- 添加数据列到数据表
dt = dotnetobject "system.data.DataTable" "Test"
Column1 = dotnetobject "System.Data.DataColumn" "id" (dotnetclass "System.Int32")
Column2 = dotnetobject "System.Data.DataColumn" "Name" (dotnetclass "System.String")
dt.columns.add Column1
dt.columns.add Column2
-- 添加数据行
for i = 0 to 2 do (
row = #(dotnetobject "System.Int32" i, dotnetobject "System.String" (i as string))
dt.rows.add row
)
-- 创建数据网格并绑定数据源
DGrid1 = dotnetobject "System.Windows.Forms.DataGrid"
DGrid1.Location = dotNetObject "System.Drawing.Point" 10 10
DGrid1.Width = 365
DGrid1.Height = 120
DGrid1.Visible = true
DGrid1.DataSource = dt
)
-- 获取文件信息
FileName = maxFilePath + maxFileName
FileInfo = dotNetObject "System.IO.FileInfo" FileName
-- 格式化时间
Hour = (FileInfo.LastWriteTime.Hour as string) + ":" + (FileInfo.LastWriteTime.Minute as string) + ":" + (FileInfo.LastWriteTime.Second as string)
Date = FileInfo.LastWriteTime.DayOfWeek.ToString() + " " + (FileInfo.LastWriteTime.Month as string) + "/" + (FileInfo.LastWriteTime.Day as string) + "/" + (FileInfo.LastWriteTime.Year as string)
Print "Last Write Time on " + Date + " at " + Hour
-- 比较文件时间
if file1.GetLastWriteTime().ticks < file2.GetLastWriteTime().ticks then
-- 文件1比文件2旧
DateTime = dotNetClass "System.DateTime"
date1 = fileInfo1.GetLastWriteTime()
date2 = fileInfo2.GetLastWriteTime()
compare = DateTime.Compare date1 date2
if compare < 0 then
Print "date1 is less than date2"
else if compare == 0 then
Print "date1 equals date2"
else -- compare > 0
Print "date1 is greater than date2"
-- C#代码等效的MaxScript
local ofd = dotnetobject "System.Windows.Forms.OpenFileDialog"
ofd.Filter = "XML Files (*.xml)|*.xml"
ofd.RestoreDirectory = false
ofd.multiselect = true
if ofd.showDialog() == (dotNetClass "System.Windows.Forms.DialogResult").OK then (
local sFile = ofd.fileNames
-- 在这里处理文件数组...
)
-- .NET数组索引从0开始!
-- 创建包含10个整数的.NET数组
intArray = dotNetObject "System.Int32[]" 10
-- 填充数组
for idx = 1 to 10 do (
intValue = dotNetObject "System.Int32" (random 1 100)
intIndex = dotNetObject "System.Int32" (idx-1)
intArray.SetValue intValue intIndex
)
-- 打印数组数据
for idx = 1 to 10 do (
intIndex = dotNetObject "System.Int32" (idx-1)
print (intArray.GetValue intIndex)
)
(
tv = dotNetObject "System.Windows.Forms.TableLayoutPanel"
tv.layoutSettings.RowCount = 12
tv.layoutSettings.ColumnCount = 6
tv.BorderStyle = (dotNetClass "System.Windows.Forms.BorderStyle").None
tv.CellBorderStyle = (dotNetClass "System.Windows.Forms.TableLayoutPanelCellBorderStyle").Single
tv.width = tv.layoutSettings.ColumnCount * 32
tv.height = tv.layoutSettings.RowCount * 32
)
(
-- 加载必要的程序集
dotNet.loadAssembly "System"
dotNet.loadAssembly "System.Core"
-- 定义C#代码(使用普通字符串,注意转义双引号)
csharpCode = "using System;\nusing System.Windows.Forms;\n\npublic class MyTestClass\n{\n public static string GetMessage()\n {\n return \"Hello from dynamically compiled C#!\";\n }\n \n public static int Add(int a, int b)\n {\n return a + b;\n }\n \n public void ShowMessage(string message)\n {\n MessageBox.Show(message);\n }\n}"
-- 创建编译器参数
provider = dotNetObject "Microsoft.CSharp.CSharpCodeProvider"
compilerParams = dotNetObject "System.CodeDom.Compiler.CompilerParameters"
-- 设置编译参数
compilerParams.GenerateInMemory = true
compilerParams.GenerateExecutable = false
compilerParams.ReferencedAssemblies.Add "System.dll"
compilerParams.ReferencedAssemblies.Add "System.Windows.Forms.dll"
-- 编译代码
results = provider.CompileAssemblyFromSource compilerParams #(csharpCode)
-- 检查编译错误
if results.Errors.Count > 0 then (
format "编译错误:\n"
for i = 0 to (results.Errors.Count - 1) do (
error = results.Errors.Item[i]
format "行 %: %\n" error.Line error.ErrorText
)
) else (
format "编译成功!\n"
-- 编译成功后,程序集会自动加载到MaxScript的dotnet环境中
try (
-- 直接使用dotNetClass访问静态方法
myTestClass = dotNetClass "MyTestClass"
-- 调用静态方法GetMessage
message = myTestClass.GetMessage()
format "%\n" message
-- 调用带参数的静态方法Add
sum = myTestClass.Add 5 3
format "5 + 3 = %\n" sum
-- 创建实例并调用实例方法
instance = dotNetObject "MyTestClass"
instance.ShowMessage "动态编译成功!"
)
catch (
format "错误: %\n" (getCurrentException())
)
)
)
(
-- 定义包含窗体的C#代码
csharpCode = "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\npublic class DynamicForm : Form\n{\n private Button button1;\n private TextBox textBox1;\n \n public DynamicForm()\n {\n this.Text = \"动态编译的窗体\";\n this.Size = new Size(400, 300);\n this.StartPosition = FormStartPosition.CenterScreen;\n \n button1 = new Button();\n button1.Text = \"点击我\";\n button1.Location = new Point(150, 150);\n button1.Size = new Size(100, 30);\n button1.Click += new EventHandler(ButtonClick);\n \n textBox1 = new TextBox();\n textBox1.Location = new Point(50, 50);\n textBox1.Size = new Size(300, 100);\n textBox1.Multiline = true;\n textBox1.ScrollBars = ScrollBars.Vertical;\n \n this.Controls.Add(button1);\n this.Controls.Add(textBox1);\n }\n \n private void ButtonClick(object sender, EventArgs e)\n {\n textBox1.Text = \"按钮被点击了!\\n时间: \" + DateTime.Now.ToString();\n }\n \n public void SetText(string text)\n {\n textBox1.Text = text;\n }\n}"
-- 编译代码
provider = dotnetobject "Microsoft.CSharp.CSharpCodeProvider"
compilerParams = dotnetobject "System.CodeDom.Compiler.CompilerParameters"
compilerParams.GenerateInMemory = true
compilerParams.ReferencedAssemblies.Add "System.dll"
compilerParams.ReferencedAssemblies.Add "System.Windows.Forms.dll"
compilerParams.ReferencedAssemblies.Add "System.Drawing.dll"
results = provider.CompileAssemblyFromSource compilerParams #(csharpCode)
if results.Errors.Count == 0 then (
assembly = results.CompiledAssembly
formType = assembly.GetType "DynamicForm"
form = assembly.CreateInstance "DynamicForm"
-- 显示窗体
form.ShowDialog()
)
)
(
-- 定义自定义控件
csharpCode = "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\npublic class ColorButton : Button\n{\n private Color normalColor = Color.LightBlue;\n private Color hoverColor = Color.LightGreen;\n private Color clickColor = Color.LightCoral;\n \n public ColorButton()\n {\n this.BackColor = normalColor;\n this.Size = new Size(120, 40);\n this.FlatStyle = FlatStyle.Flat;\n \n this.MouseEnter += new EventHandler(OnMouseEnter);\n this.MouseLeave += new EventHandler(OnMouseLeave);\n this.MouseDown += new MouseEventHandler(OnMouseDown);\n this.MouseUp += new MouseEventHandler(OnMouseUp);\n }\n \n private void OnMouseEnter(object sender, EventArgs e)\n {\n this.BackColor = hoverColor;\n }\n \n private void OnMouseLeave(object sender, EventArgs e)\n {\n this.BackColor = normalColor;\n }\n \n private void OnMouseDown(object sender, MouseEventArgs e)\n {\n this.BackColor = clickColor;\n }\n \n private void OnMouseUp(object sender, MouseEventArgs e)\n {\n this.BackColor = hoverColor;\n }\n}"
-- 编译并使用自定义控件
provider = dotNetObject "Microsoft.CSharp.CSharpCodeProvider"
compilerParams = dotNetObject "System.CodeDom.Compiler.CompilerParameters"
compilerParams.GenerateInMemory = true
compilerParams.ReferencedAssemblies.Add "System.dll"
compilerParams.ReferencedAssemblies.Add "System.Windows.Forms.dll"
compilerParams.ReferencedAssemblies.Add "System.Drawing.dll"
results = provider.CompileAssemblyFromSource compilerParams #(csharpCode)
if results.Errors.Count == 0 then (
assembly = results.CompiledAssembly
buttonType = assembly.GetType "ColorButton"
-- 在rollout中使用自定义控件
rollout testRollout "自定义控件测试" width:200 height:100
(
dotNetControl customBtn "ColorButton" pos:[40, 30]
on customBtn click do
(
format "自定义按钮被点击!\n"
)
)
createDialog testRollout
)
)
(
Color = dotNetClass "System.Drawing.Color"
-- 创建TreeView控件
treeView = dotNetObject "System.Windows.Forms.TreeView"
treeView.Location = dotNetObject "System.Drawing.Point" 10 10
treeView.Width = 280
treeView.Height = 250
treeView.BackColor = Color.White
-- 创建根节点
rootNode1 = dotNetObject "System.Windows.Forms.TreeNode" "场景对象"
rootNode2 = dotNetObject "System.Windows.Forms.TreeNode" "材质"
rootNode3 = dotNetObject "System.Windows.Forms.TreeNode" "动画"
-- 添加子节点
childNode1 = dotNetObject "System.Windows.Forms.TreeNode" "几何体"
childNode2 = dotNetObject "System.Windows.Forms.TreeNode" "灯光"
childNode3 = dotNetObject "System.Windows.Forms.TreeNode" "相机"
childNode4 = dotNetObject "System.Windows.Forms.TreeNode" "标准材质"
childNode5 = dotNetObject "System.Windows.Forms.TreeNode" "V-Ray材质"
-- 构建树形结构
rootNode1.Nodes.Add childNode1
rootNode1.Nodes.Add childNode2
rootNode1.Nodes.Add childNode3
rootNode2.Nodes.Add childNode4
rootNode2.Nodes.Add childNode5
treeView.Nodes.Add rootNode1
treeView.Nodes.Add rootNode2
treeView.Nodes.Add rootNode3
-- 展开所有节点
treeView.ExpandAll()
-- 创建窗体
form = dotNetObject "System.Windows.Forms.Form"
form.Size = dotNetObject "System.Drawing.Size" 310 300
form.Text = "TreeView示例"
form.Controls.Add treeView
form.TopMost = true
-- 显示窗体
app = dotNetClass "System.Windows.Forms.Application"
app.Run form
)
(
Color = dotNetClass "System.Drawing.Color"
-- 创建ListView控件
listView = dotNetObject "System.Windows.Forms.ListView"
listView.Location = dotNetObject "System.Drawing.Point" 10 10
listView.Width = 380
listView.Height = 250
listView.View = (dotNetClass "System.Windows.Forms.View").Details
listView.FullRowSelect = true
listView.GridLines = true
listView.BackColor = Color.White
-- 添加列
listView.Columns.Add "名称" 100
listView.Columns.Add "类型" 80
listView.Columns.Add "多边形数" 100
listView.Columns.Add "状态" 80
-- 添加数据项
for i = 1 to 5 do (
item = dotNetObject "System.Windows.Forms.ListViewItem" ("对象 " + (i as string))
item.SubItems.Add "几何体"
item.SubItems.Add ((random 100 1000) as string)
item.SubItems.Add "正常"
listView.Items.Add item
)
-- 创建窗体
form = dotNetObject "System.Windows.Forms.Form"
form.Size = dotNetObject "System.Drawing.Size" 410 300
form.Text = "ListView示例"
form.Controls.Add listView
form.TopMost = true
-- 显示窗体
app = dotNetClass "System.Windows.Forms.Application"
app.Run form
)
(
Color = dotNetClass "System.Drawing.Color"
-- 创建进度条
progressBar = dotNetObject "System.Windows.Forms.ProgressBar"
progressBar.Location = dotNetObject "System.Drawing.Point" 20 50
progressBar.Width = 260
progressBar.Height = 23
progressBar.Minimum = 0
progressBar.Maximum = 100
progressBar.Value = 0
-- 创建按钮
button = dotNetObject "System.Windows.Forms.Button"
button.Text = "开始"
button.Location = dotNetObject "System.Drawing.Point" 120 90
button.Size = dotNetObject "System.Drawing.Size" 75 30
-- 创建窗体
form = dotNetObject "System.Windows.Forms.Form"
form.Size = dotNetObject "System.Drawing.Size" 320 180
form.Text = "进度条示例"
form.Controls.Add progressBar
form.Controls.Add button
form.TopMost = true
-- 定义按钮点击事件处理函数
fn onButtonClicked sender e = (
for i = 1 to 100 do (
progressBar.Value = i
-- 模拟处理
windows.processPostedMessages()
)
(dotNetClass "System.Windows.Forms.MessageBox").Show "处理完成!"
)
-- 注册事件处理器
dotNet.addEventHandler button "Click" onButtonClicked
-- 显示窗体
app = dotNetClass "System.Windows.Forms.Application"
app.Run form
)
(
-- 获取指定目录下的所有文件
dirPath = "C:\\Temp"
directoryInfo = dotNetObject "System.IO.DirectoryInfo" dirPath
-- 获取所有文件
files = directoryInfo.GetFiles()
format "目录 % 中的文件:\n" dirPath
for i = 1 to files.count do (
file = files[i]
format " % - % 字节\n" file.Name file.Length
)
-- 获取所有子目录
directories = directoryInfo.GetDirectories()
format "\n子目录:\n"
for i = 1 to directories.count do (
dir = directories[i]
format " %\n" dir.Name
)
)
(
-- 复制文件
sourceFile = "C:\\Temp\\source.txt"
destFile = "C:\\Temp\\backup.txt"
if (dotNetClass "System.IO.File").Exists sourceFile then (
(dotNetClass "System.IO.File").Copy sourceFile destFile true
format "文件已复制到 %\n" destFile
)
-- 移动文件
newLocation = "C:\\Temp\\moved.txt"
if (dotNetClass "System.IO.File").Exists destFile then (
(dotNetClass "System.IO.File").Move destFile newLocation
format "文件已移动到 %\n" newLocation
)
)
(
-- 创建目录
newDir = "C:\\Temp\\NewFolder"
if not ((dotNetClass "System.IO.Directory").Exists newDir) then (
(dotNetClass "System.IO.Directory").CreateDirectory newDir
format "目录已创建: %\n" newDir
)
-- 删除目录
if (dotNetClass "System.IO.Directory").Exists newDir then (
(dotNetClass "System.IO.Directory").Delete newDir true
format "目录已删除: %\n" newDir
)
)
(
-- 创建WebClient
webClient = dotNetObject "System.Net.WebClient"
-- 添加用户代理
webClient.Headers.Add "User-Agent" "MaxScript/1.0"
try (
-- 下载网页内容
url = "http://www.example.com"
response = webClient.DownloadString url
format "响应内容:\n%\n" response
) catch (
format "请求失败: %\n" (getCurrentException())
)
-- 释放资源
webClient.Dispose()
)
(
-- 创建WebClient
webClient = dotNetObject "System.Net.WebClient"
webClient.Headers.Add "Content-Type" "application/x-www-form-urlencoded"
try (
-- 准备POST数据
postData = "name=test&value=123"
-- 使用.NET方法将字符串转换为字节数组
encoding = dotNetClass "System.Text.Encoding"
data = encoding.ASCII.GetBytes postData
-- 发送POST请求
url = "http://www.example.com/api"
response = webClient.UploadData url data
format "响应: %\n" response
) catch (
format "请求失败: %\n" (getCurrentException())
)
webClient.Dispose()
)
(
-- 创建正则表达式(注意:MaxScript中不需要@符号)
regex = dotNetObject "System.Text.RegularExpressions.Regex" "\\d+"
-- 测试字符串
testString = "abc123def456ghi789"
-- 查找所有匹配
matches = regex.Matches testString
format "找到 % 个匹配:\n" matches.Count
for i = 0 to (matches.Count - 1) do (
match = matches.Item[i]
format " 匹配 %: %\n" (i+1) match.Value
)
)
(
-- 创建正则表达式
regex = dotNetObject "System.Text.RegularExpressions.Regex" "\\b\\w{4}\\b"
-- 替换字符串
input = "This is a test string with some words"
output = regex.Replace input "****"
format "原始: %\n" input
format "替换: %\n" output
)
(
-- 验证电子邮件格式
emailRegex = dotNetObject "System.Text.RegularExpressions.Regex" "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
emails = #("test@example.com", "invalid.email", "user@domain.co")
for email in emails do (
if emailRegex.IsMatch email then (
format "% - 有效\n" email
) else (
format "% - 无效\n" email
)
)
)
(
-- 创建Timer
timer = dotNetObject "System.Windows.Forms.Timer"
timer.Interval = 1000
counter = 0
-- 定义Tick事件处理
fn onTimerTick sender e = (
counter += 1
format "计时器触发: %\n" counter
if counter >= 5 then (
sender.Stop()
format "计时器停止\n"
)
)
dotNet.addEventHandler timer "Tick" onTimerTick
-- 启动计时器
timer.Start()
format "计时器已启动\n"
)
(
-- 创建后台工作线程
backgroundWorker = dotNetObject "System.ComponentModel.BackgroundWorker"
backgroundWorker.WorkerReportsProgress = true
-- 定义DoWork事件
fn onDoWork sender e = (
for i = 1 to 10 do (
sender.ReportProgress (i * 10)
-- 模拟工作
windows.processPostedMessages()
)
)
dotNet.addEventHandler backgroundWorker "DoWork" onDoWork
-- 定义ProgressChanged事件
fn onProgressChanged sender e = (
-- 使用多个format调用避免%符号冲突
format "进度: "
format (e.ProgressPercentage as string)
format "%\n" "%"
)
dotNet.addEventHandler backgroundWorker "ProgressChanged" onProgressChanged
-- 启动后台任务
backgroundWorker.RunWorkerAsync()
)
(
-- 定义数据类
csharpCode = "using System;\nusing System.Collections.Generic;\nusing System.Web.Script.Serialization;\n\npublic class Person\n{\n public string Name { get; set; }\n public int Age { get; set; }\n public List<string> Hobbies { get; set; }\n \n public Person()\n {\n Hobbies = new List<string>();\n }\n \n public string ToJson()\n {\n JavaScriptSerializer serializer = new JavaScriptSerializer();\n return serializer.Serialize(this);\n }\n \n public static Person FromJson(string json)\n {\n JavaScriptSerializer serializer = new JavaScriptSerializer();\n return serializer.Deserialize<Person>(json);\n }\n}"
-- 编译代码
provider = dotnetobject "Microsoft.CSharp.CSharpCodeProvider"
compilerParams = dotnetobject "System.CodeDom.Compiler.CompilerParameters"
compilerParams.GenerateInMemory = true
compilerParams.ReferencedAssemblies.Add "System.dll"
compilerParams.ReferencedAssemblies.Add "System.Web.Extensions.dll"
results = provider.CompileAssemblyFromSource compilerParams #(csharpCode)
if results.Errors.Count == 0 then (
-- 编译成功后,程序集会自动加载到MaxScript的dotnet环境中
-- 创建对象
person = dotNetObject "Person"
person.Name = "张三"
person.Age = 30
person.Hobbies.Add "编程"
person.Hobbies.Add "阅读"
-- 序列化为JSON
json = person.ToJson()
format "JSON: %\n" json
-- 从JSON反序列化
person2 = (dotNetClass "Person").FromJson json
format "姓名: %, 年龄: %\n" person2.Name person2.Age
)
)
(
-- 获取计算机名称
computerName = (dotNetClass "System.Environment").MachineName
format "计算机名: %\n" computerName
-- 获取用户名
userName = (dotNetClass "System.Environment").UserName
format "用户名: %\n" userName
-- 获取操作系统版本
osVersion = (dotNetClass "System.Environment").OSVersion
format "操作系统: %\n" osVersion.ToString()
-- 获取系统目录
systemDirectory = (dotNetClass "System.Environment").SystemDirectory
format "系统目录: %\n" systemDirectory
-- 获取处理器数量
processorCount = (dotNetClass "System.Environment").ProcessorCount
format "处理器数量: %\n" processorCount
-- 获取内存信息
workingSet = (dotNetClass "System.Environment").WorkingSet
format "工作集内存: % MB\n" (workingSet / (1024 * 1024) as integer)
)
(
-- 获取所有环境变量
envVars = (dotNetClass "System.Environment").GetEnvironmentVariables()
format "环境变量:\n"
-- 使用DictionaryEntry遍历Hashtable
enumerator = envVars.GetEnumerator()
while enumerator.MoveNext() do (
entry = enumerator.Current
key = entry.Key
value = entry.Value
format " % = %\n" key value
)
-- 获取特定环境变量
pathVar = (dotNetClass "System.Environment").GetEnvironmentVariable "PATH"
format "\nPATH: %\n" pathVar
)
(
-- 定义带事件的类
csharpCode = "using System;\n\npublic class EventPublisher\n{\n public event EventHandler SomethingHappened;\n \n public void DoSomething()\n {\n OnSomethingHappened(EventArgs.Empty);\n }\n \n protected virtual void OnSomethingHappened(EventArgs e)\n {\n if (SomethingHappened != null)\n {\n SomethingHappened(this, e);\n }\n }\n}"
-- 编译代码
provider = dotnetobject "Microsoft.CSharp.CSharpCodeProvider"
compilerParams = dotnetobject "System.CodeDom.Compiler.CompilerParameters"
compilerParams.GenerateInMemory = true
compilerParams.ReferencedAssemblies.Add "System.dll"
results = provider.CompileAssemblyFromSource compilerParams #(csharpCode)
if results.Errors.Count == 0 then (
-- 编译成功后,程序集会自动加载到MaxScript的dotnet环境中
-- 创建发布者
publisher = dotNetObject "EventPublisher"
-- 订阅事件
fn onSomethingHappened sender e = (
format "事件触发!\n"
)
dotNet.addEventHandler publisher "SomethingHappened" onSomethingHappened
-- 触发事件
publisher.DoSomething()
)
)
(
-- 创建PictureBox
pictureBox = dotNetObject "System.Windows.Forms.PictureBox"
pictureBox.Width = 400
pictureBox.Height = 300
pictureBox.BackColor = (dotNetClass "System.Drawing.Color").White
-- 创建位图
bitmap = dotNetObject "System.Drawing.Bitmap" 400 300
graphics = dotNetClass "System.Drawing.Graphics"
g = graphics.FromImage bitmap
-- 清除背景
g.Clear (dotNetClass "System.Drawing.Color").White
-- 绘制矩形
redBrush = dotNetObject "System.Drawing.SolidBrush" (dotNetClass "System.Drawing.Color").Red
g.FillRectangle redBrush 50 50 100 80
-- 绘制圆形
blueBrush = dotNetObject "System.Drawing.SolidBrush" (dotNetClass "System.Drawing.Color").Blue
g.FillEllipse blueBrush 200 50 80 80
-- 绘制线条
blackPen = dotNetObject "System.Drawing.Pen" (dotNetClass "System.Drawing.Color").Black 2
g.DrawLine blackPen 50 200 350 200
-- 绘制文本
font = dotNetObject "System.Drawing.Font" "Arial" 16
blackBrush = dotNetObject "System.Drawing.SolidBrush" (dotNetClass "System.Drawing.Color").Black
g.DrawString "Hello from MaxScript!" font blackBrush 50 250
-- 设置图片
pictureBox.Image = bitmap
-- 创建窗体
form = dotNetObject "System.Windows.Forms.Form"
form.Size = dotNetObject "System.Drawing.Size" 420 340
form.Text = "图形绘制示例"
form.Controls.Add pictureBox
form.TopMost = true
-- 显示窗体
app = dotNetClass "System.Windows.Forms.Application"
app.Run form
)
(
-- 创建List
intList = dotNetObject "System.Collections.Generic.List`1[System.Int32]"
-- 添加元素
for i = 1 to 10 do (
intList.Add (random 1 100)
)
format "列表元素:\n"
for i = 0 to (intList.Count - 1) do (
format " %\n" (intList.Item i)
)
-- 排序
intList.Sort()
format "\n排序后:\n"
for i = 0 to (intList.Count - 1) do (
format " %\n" (intList.Item i)
)
-- 查找
searchValue = 50
index = intList.IndexOf searchValue
if index >= 0 then (
format "\n找到 % 在位置 %\n" searchValue index
) else (
format "\n未找到 %\n" searchValue
)
)
-- 创建Dictionary
dict = dotNetObject "System.Collections.Generic.Dictionary`2[System.String, System.Int32]"
-- 添加键值对
dict.Add "苹果" 10
dict.Add "香蕉" 20
dict.Add "橙子" 15
-- 遍历字典
format "字典内容:\n"
enumerator = dict.GetEnumerator()
while enumerator.MoveNext() do (
entry = enumerator.Current
key = entry.Key
value = entry.Value
format " %: %\n" key value
)
-- 查找值
searchKey = "香蕉"
if dict.ContainsKey searchKey then (
format "\n% 的数量: %\n" searchKey (dict.Item searchKey)
)
-- 更新值
dict.set_Item "苹果" 25
format "\n更新后苹果的数量: %\n" (dict.Item "苹果")
(
-- 读取文件内容(指定编码)
filePath = "C:\\Temp\\test.txt"
if ((dotNetClass "System.IO.File").Exists filePath) then (
-- 读取UTF-8编码的文件
encoding = dotNetClass "System.Text.Encoding"
content = (dotNetClass "System.IO.File").ReadAllText filePath encoding.UTF8
format "文件内容:\n%\n" content
-- 写入文件(指定编码)
newContent = "新的内容"
(dotNetClass "System.IO.File").WriteAllText filePath newContent encoding.UTF8
format "文件已更新\n"
)
)
(
path = dotNetClass "System.IO.Path"
-- 组合路径
fullPath = path.Combine "C:\\Temp" "subfolder" "file.txt"
format "完整路径: %\n" fullPath
-- 获取文件名
fileName = path.GetFileName fullPath
format "文件名: %\n" fileName
-- 获取目录名
directoryName = path.GetDirectoryName fullPath
format "目录名: %\n" directoryName
-- 获取扩展名
extension = path.GetExtension fullPath
format "扩展名: %\n" extension
-- 获取不带扩展名的文件名
fileNameWithoutExt = path.GetFileNameWithoutExtension fullPath
format "不带扩展名的文件名: %\n" fileNameWithoutExt
-- 获取临时路径
tempPath = path.GetTempPath()
format "临时路径: %\n" tempPath
-- 获取随机文件名
randomFileName = path.GetRandomFileName()
format "随机文件名: %\n" randomFileName
)
(
-- 错误方式:字符串拼接
startTime = timeStamp()
str = ""
for i = 1 to 10000 do (
str += "a"
)
endTime = timeStamp()
format "字符串拼接耗时: % 毫秒\n" (endTime - startTime)
-- 正确方式:使用StringBuilder
startTime = timeStamp()
sb = dotNetObject "System.Text.StringBuilder"
for i = 1 to 10000 do (
sb.Append "a"
)
str2 = sb.ToString()
endTime = timeStamp()
format "StringBuilder耗时: % 毫秒\n" (endTime - startTime)
)
(
-- 创建Stopwatch
stopwatch = dotNetObject "System.Diagnostics.Stopwatch"
-- 开始计时
stopwatch.Start()
-- 执行一些操作
for i = 1 to 1000 do (
-- 模拟工作
)
-- 停止计时
stopwatch.Stop()
format "耗时: % 毫秒\n" stopwatch.ElapsedMilliseconds
format "耗时: % 秒\n" stopwatch.Elapsed.TotalSeconds
)
(
-- 使用Debug.WriteLine
debug = dotNetClass "System.Diagnostics.Debug"
debug.WriteLine "这是一条调试信息"
debug.WriteLine "变量值: 123"
-- 使用Debug.Assert
x = 5
debug.Assert (x > 10) "x应该大于10"
-- 使用Debug.Print
debug.Print "打印信息"
)
(
-- 使用Trace.WriteLine
trace = dotNetClass "System.Diagnostics.Trace"
trace.WriteLine "这是一条跟踪信息"
-- 使用Trace.WriteLineIf
condition = true
trace.WriteLineIf condition "条件为真时输出"
-- 使用Trace.Indent
trace.Indent()
trace.WriteLine "缩进的信息"
trace.Unindent()
trace.WriteLine "取消缩进的信息"
)
(
try (
-- 尝试读取不存在的文件
content = (dotNetClass "System.IO.File").ReadAllText "C:\\nonexistent.txt"
) catch (
ex = getCurrentException()
-- 检查异常类型
if (dotNetClass "System.IO.FileNotFoundException").IsInstanceOfType ex then (
format "文件未找到异常: %\n" ex.Message
) else if (dotNetClass "System.UnauthorizedAccessException").IsInstanceOfType ex then (
format "访问被拒绝异常: %\n" ex.Message
) else (
format "其他异常: %\n" ex.Message
)
)
)
(
fileStream = undefined
try (
-- 打开文件
fileStream = (dotNetClass "System.IO.File").OpenRead "C:\\Temp\\test.txt"
-- 读取文件
reader = dotNetObject "System.IO.StreamReader" fileStream
content = reader.ReadToEnd()
format "文件内容: %\n" content
) catch (
format "发生错误: %\n" (getCurrentException()).Message
) finally (
-- 确保资源被释放
if fileStream != undefined then (
fileStream.Close()
format "文件流已关闭\n"
)
)
)
-- 创建MaxScript包装器
(
-- 定义C#代码
csharpCode = "using System;
using System.IO;
using System.Text;
public class MaxScriptUtils
{
public static string ReadFileContent(string filePath)
{
try
{
return File.ReadAllText(filePath, Encoding.UTF8);
}
catch (Exception ex)
{
return \"Error: \" + ex.Message;
}
}
public static bool WriteFileContent(string filePath, string content)
{
try
{
File.WriteAllText(filePath, content, Encoding.UTF8);
return true;
}
catch (Exception ex)
{
return false;
}
}
public static string[] GetFilesInDirectory(string directoryPath)
{
try
{
return Directory.GetFiles(directoryPath);
}
catch (Exception ex)
{
return new string[] { \"Error: \" + ex.Message };
}
}
}"
-- 创建编译器参数
compilerParams = dotNetObject "System.CodeDom.Compiler.CompilerParameters"
compilerParams.GenerateInMemory = true
-- 正确实例化CSharpCodeProvider
provider = dotNetObject "Microsoft.CSharp.CSharpCodeProvider"
-- 编译代码
results = provider.CompileAssemblyFromSource compilerParams #(csharpCode)
-- 检查编译结果
if results.Errors.HasErrors then (
format "编译错误:\n"
for i = 0 to (results.Errors.Count - 1) do (
error = results.Errors.Item[i]
format " 第%行: %\n" error.Line error.ErrorText
)
) else (
format "编译成功!\n"
-- 编译成功后,程序集会自动加载到MaxScript的dotnet环境中
-- 可以直接使用dotnetclass访问静态方法
try (
-- 测试文件操作
testFile = (getDir #temp) + "\\test.txt"
content = "Hello from MaxScript wrapper!"
-- 写入文件
success = (dotNetClass "MaxScriptUtils").WriteFileContent testFile content
if success then (
format "文件写入成功: %\n" testFile
-- 读取文件
content = (dotNetClass "MaxScriptUtils").ReadFileContent testFile
format "文件内容: %\n" content
)
-- 测试目录文件获取
files = (dotNetClass "MaxScriptUtils").GetFilesInDirectory (getDir #temp)
format "\n临时目录中的文件:\n"
for i = 1 to files.count do (
format " %\n" files[i]
)
)
catch (
format "错误: %\n" (getCurrentException())
)
)
)
-- 综合应用示例:场景导出工具
(
-- 定义C#代码
csharpCode = "using System;
using System.IO;
using System.Windows.Forms;
using System.Text;
public class SceneExportTool
{
private string exportPath;
private StringBuilder exportLog;
public SceneExportTool()
{
exportLog = new StringBuilder();
exportPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
}
public string ExportPath
{
get { return exportPath; }
set { exportPath = value; }
}
public bool SelectExportPath()
{
using (FolderBrowserDialog dialog = new FolderBrowserDialog())
{
dialog.Description = \"选择导出路径\";
dialog.SelectedPath = exportPath;
dialog.ShowNewFolderButton = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
exportPath = dialog.SelectedPath;
return true;
}
}
return false;
}
public void Log(string message)
{
string logMessage = string.Format(\"[{0}] {1}\", DateTime.Now.ToString(\"HH:mm:ss\"), message);
exportLog.AppendLine(logMessage);
}
public string GetLog()
{
return exportLog.ToString();
}
public bool SaveLog(string fileName)
{
try
{
string fullPath = Path.Combine(exportPath, fileName);
File.WriteAllText(fullPath, exportLog.ToString(), Encoding.UTF8);
return true;
}
catch (Exception ex)
{
Log(\"保存日志失败: \" + ex.Message);
return false;
}
}
public void ClearLog()
{
exportLog.Clear();
}
}"
-- 创建编译器参数
compilerParams = dotNetObject "System.CodeDom.Compiler.CompilerParameters"
compilerParams.GenerateInMemory = true
compilerParams.ReferencedAssemblies.Add "System.dll"
compilerParams.ReferencedAssemblies.Add "System.Windows.Forms.dll"
compilerParams.ReferencedAssemblies.Add "System.Drawing.dll"
-- 正确实例化CSharpCodeProvider
provider = dotNetObject "Microsoft.CSharp.CSharpCodeProvider"
-- 编译代码
results = provider.CompileAssemblyFromSource compilerParams #(csharpCode)
-- 检查编译结果
if results.Errors.HasErrors then (
format "编译错误:\n"
for i = 0 to (results.Errors.Count - 1) do (
error = results.Errors.Item[i]
format " 第%行: %\n" error.Line error.ErrorText
)
) else (
format "编译成功!\n"
-- 编译成功后,程序集会自动加载到MaxScript的dotnet环境中
try (
-- 创建工具实例
exportTool = dotNetObject "SceneExportTool"
-- 显示当前导出路径
format "当前导出路径: %\n" exportTool.ExportPath
-- 选择导出路径
if exportTool.SelectExportPath() then (
format "新导出路径: %\n" exportTool.ExportPath
)
-- 记录日志
exportTool.Log "开始导出场景"
exportTool.Log "正在收集对象..."
exportTool.Log "正在处理材质..."
exportTool.Log "导出完成!"
-- 显示日志
format "\n导出日志:\n%\n" exportTool.GetLog()
-- 保存日志
if exportTool.SaveLog "export_log.txt" then (
format "日志已保存到: %\\export_log.txt\n" exportTool.ExportPath
)
)
catch (
format "错误: %\n" (getCurrentException())
)
)
)
本文档提供了在3ds Max MaxScript中使用.NET进行文件操作的详细示例。
-- 检查文件是否存在
(
local filePath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\test_file.txt"
local fileExists = (dotNetClass "System.IO.File").Exists filePath
if fileExists then
format "文件存在: %\n" filePath
else
format "文件不存在: %\n" filePath
)
-- 创建新文件
(
local filePath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\new_file.txt"
local content = "这是新创建的文件内容"
local encoding = dotNetClass "System.Text.Encoding"
(dotNetClass "System.IO.File").WriteAllText filePath content encoding.UTF8
format "文件已创建: %\n" filePath
)
-- 删除文件
(
local filePath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\temp_file.txt"
if (dotNetClass "System.IO.File").Exists filePath then
(
(dotNetClass "System.IO.File").Delete filePath
format "文件已删除: %\n" filePath
)
)
-- 获取文件信息
(
local filePath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\test_file.txt"
local fileInfo = dotNetObject "System.IO.FileInfo" filePath
format "文件名: %\n" fileInfo.Name
format "完整路径: %\n" fileInfo.FullName
format "文件大小: % 字节\n" fileInfo.Length
format "创建时间: %\n" fileInfo.LastWriteTime.ToString()
format "最后修改时间: %\n" fileInfo.LastWriteTime.ToString()
format "最后访问时间: %\n" fileInfo.LastAccessTime.ToString()
format "是否为只读: %\n" fileInfo.IsReadOnly
format "扩展名: %\n" fileInfo.Extension
)
-- 获取文件所在目录
(
local filePath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\test_file.txt"
local fileInfo = dotNetObject "System.IO.FileInfo" filePath
local directoryInfo = fileInfo.Directory
format "文件所在目录: %\n" directoryInfo.FullName
format "目录是否存在: %\n" directoryInfo.Exists
)
-- 比较两个文件的修改时间
(
local filePath1 = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\test_file.txt"
local filePath2 = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\new_file.txt"
local fileInfo1 = dotNetObject "System.IO.FileInfo" filePath1
local fileInfo2 = dotNetObject "System.IO.FileInfo" filePath2
local time1 = fileInfo1.LastWriteTime
local time2 = fileInfo2.LastWriteTime
local compareResult = (dotNetClass "System.DateTime").Compare time1 time2
if compareResult < 0 then
format "% 比 % 旧\n" filePath1 filePath2
else if compareResult == 0 then
format "% 和 % 修改时间相同\n" filePath1 filePath2
else
format "% 比 % 新\n" filePath1 filePath2
)
-- 检查文件是否在指定时间之后修改
(
local filePath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\test_file.txt"
local fileInfo = dotNetObject "System.IO.FileInfo" filePath
-- 指定一个时间点(例如1小时前)
local checkTime = (dotNetClass "System.DateTime").Now.AddHours -1
local fileTime = fileInfo.LastWriteTime
-- 使用DateTime.Compare方法比较时间
local compareResult = (dotNetClass "System.DateTime").Compare fileTime checkTime
if compareResult > 0 then
format "文件在过去1小时内被修改过\n"
else
format "文件在过去1小时内未被修改过\n"
)
-- 复制文件
(
local sourcePath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\test_file.txt"
local destPath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\test_file_copy.txt"
-- 第三个参数为true表示覆盖已存在的文件
(dotNetClass "System.IO.File").Copy sourcePath destPath true
format "文件已复制: % -> %\n" sourcePath destPath
)
-- 移动文件
(
local sourcePath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\test_file_copy.txt"
local destPath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\moved_file.txt"
(dotNetClass "System.IO.File").Move sourcePath destPath
format "文件已移动: % -> %\n" sourcePath destPath
)
-- 读取文件内容
(
local filePath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\test_file.txt"
local encoding = dotNetClass "System.Text.Encoding"
if (dotNetClass "System.IO.File").Exists filePath then
(
local content = (dotNetClass "System.IO.File").ReadAllText filePath encoding.UTF8
format "文件内容:\n%\n" content
)
)
-- 写入文件内容
(
local filePath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\output.txt"
local content = "这是写入的文件内容\n包含多行文本"
local encoding = dotNetClass "System.Text.Encoding"
(dotNetClass "System.IO.File").WriteAllText filePath content encoding.UTF8
format "内容已写入文件: %\n" filePath
)
-- 追加文件内容
(
local filePath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\output.txt"
local content = "\n这是追加的内容"
local encoding = dotNetClass "System.Text.Encoding"
(dotNetClass "System.IO.File").AppendAllText filePath content encoding.UTF8
format "内容已追加到文件: %\n" filePath
)
-- 创建目录
(
local dirPath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\new_directory"
if not ((dotNetClass "System.IO.Directory").Exists dirPath) then
(
(dotNetClass "System.IO.Directory").CreateDirectory dirPath
format "目录已创建: %\n" dirPath
)
else
(
format "目录已存在: %\n" dirPath
)
)
-- 删除目录
(
local dirPath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\new_directory"
if (dotNetClass "System.IO.Directory").Exists dirPath then
(
-- true表示递归删除所有子目录和文件
(dotNetClass "System.IO.Directory").Delete dirPath true
format "目录已删除: %\n" dirPath
)
)
-- 遍历目录中的文件和子目录
(
local dirPath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository"
local directoryInfo = dotNetObject "System.IO.DirectoryInfo" dirPath
-- 获取所有文件
local files = directoryInfo.GetFiles()
format "目录中的文件:\n"
-- 注意:MaxScript数组索引从1开始,不是0
for i = 1 to files.count do
(
local file = files[i]
-- 正确的ToString()方法调用
local lastWriteTime = file.LastWriteTime.ToString()
format " % (%, % bytes)\n" file.Name lastWriteTime file.Length
)
-- 获取所有子目录
local directories = directoryInfo.GetDirectories()
format "\n子目录:\n"
-- 注意:MaxScript数组索引从1开始,不是0
for i = 1 to directories.count do
(
local dir = directories[i]
-- 修复GetFiles()数组访问
local dirFiles = dir.GetFiles()
format " % (% files)\n" dir.Name dirFiles.count
)
)
-- 组合路径
(
local paths = dotNetClass "System.IO.Path"
local dirPath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository"
local fileName = "test.txt"
local fullPath = paths.Combine dirPath fileName
format "完整路径: %\n" fullPath
)
-- 提取路径信息
(
local fullPath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository\\test_file.txt"
local paths = dotNetClass "System.IO.Path"
format "完整路径: %\n" fullPath
format "文件名: %\n" (paths.GetFileName fullPath)
format "不带扩展名的文件名: %\n" (paths.GetFileNameWithoutExtension fullPath)
format "扩展名: %\n" (paths.GetExtension fullPath)
format "目录名: %\n" (paths.GetDirectoryName fullPath)
format "根目录: %\n" (paths.GetPathRoot fullPath)
)
-- 获取临时路径
(
local paths = dotNetClass "System.IO.Path"
format "临时目录: %\n" (paths.GetTempPath())
format "随机文件名: %\n" (paths.GetRandomFileName())
format "临时文件名: %\n" (paths.GetTempFileName())
)
-- 文件选择对话框
(
local ofd = dotnetobject "System.Windows.Forms.OpenFileDialog"
ofd.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*"
ofd.Title = "选择文件"
ofd.InitialDirectory = maxFilePath
ofd.Multiselect = true
if ofd.showDialog() == (dotNetClass "System.Windows.Forms.DialogResult").OK then
(
-- 获取选择的文件
local selectedFiles = ofd.FileNames
format "选择了 % 个文件:\n" selectedFiles.Length
for i = 0 to (selectedFiles.Length - 1) do
(
format " %\n" selectedFiles.GetValue i
)
)
)
-- 保存文件对话框
(
local sfd = dotnetobject "System.Windows.Forms.SaveFileDialog"
sfd.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*"
sfd.Title = "保存文件"
sfd.InitialDirectory = maxFilePath
sfd.FileName = "output.txt"
if sfd.showDialog() == (dotNetClass "System.Windows.Forms.DialogResult").OK then
(
local savePath = sfd.FileName
format "保存路径: %\n" savePath
-- 在这里写入文件内容
local content = "保存的文件内容"
(dotNetClass "System.IO.File").WriteAllText savePath content
)
)
以下是一个完整的示例脚本,演示了上述所有文件操作:
-- 文件操作完整示例
(
-- 定义测试文件路径
local basePath = "f:\\My_maxscrriptCode\\MyFile\\my-max-plugin\\Repository"
local testFilePath = basePath + "\\test_file.txt"
local outputPath = basePath + "\\output.txt"
format "=== 文件操作演示 ===\n\n"
-- 1. 检查文件是否存在
format "1. 检查文件是否存在:\n"
local fileExists = (dotNetClass "System.IO.File").Exists testFilePath
if fileExists then
format "✓ 测试文件存在\n"
else
format "✗ 测试文件不存在\n"
-- 2. 获取文件信息
format "\n2. 文件信息:\n"
if fileExists then
(
local fileInfo = dotNetObject "System.IO.FileInfo" testFilePath
format "文件名: %\n" fileInfo.Name
format "大小: % 字节\n" fileInfo.Length
format "修改时间: %\n" fileInfo.LastWriteTime.ToString()
)
-- 3. 读取文件内容
format "\n3. 文件内容:\n"
if fileExists then
(
local content = (dotNetClass "System.IO.File").ReadAllText testFilePath
format "%\n" content
)
-- 4. 写入文件
format "\n4. 写入文件:\n"
local newContent = "这是新写入的内容\n时间: " + (dotNetClass "System.DateTime").Now.ToString()
(dotNetClass "System.IO.File").WriteAllText outputPath newContent
format "✓ 内容已写入: %\n" outputPath
-- 5. 复制文件
format "\n5. 复制文件:\n"
local copyPath = basePath + "\\output_copy.txt"
(dotNetClass "System.IO.File").Copy outputPath copyPath true
format "✓ 文件已复制到: %\n" copyPath
-- 6. 移动文件
format "\n6. 移动文件:\n"
local movePath = basePath + "\\moved_output.txt"
(dotNetClass "System.IO.File").Move copyPath movePath
format "✓ 文件已移动到: %\n" movePath
-- 7. 目录操作
format "\n7. 目录操作:\n"
local testDir = basePath + "\\test_directory"
-- 创建目录
if not ((dotNetClass "System.IO.Directory").Exists testDir) then
(
(dotNetClass "System.IO.Directory").CreateDirectory testDir
format "✓ 目录已创建: %\n" testDir
)
-- 8. 清理
format "\n8. 清理:\n"
if (dotNetClass "System.IO.File").Exists outputPath then
(
(dotNetClass "System.IO.File").Delete outputPath
format "✓ 删除文件: %\n" outputPath
)
if (dotNetClass "System.IO.File").Exists movePath then
(
(dotNetClass "System.IO.File").Delete movePath
format "✓ 删除文件: %\n" movePath
)
if (dotNetClass "System.IO.Directory").Exists testDir then
(
(dotNetClass "System.IO.Directory").Delete testDir true
format "✓ 删除目录: %\n" testDir
)
format "\n=== 演示完成 ===\n"
)
\\)作为路径分隔符。通过以上示例,你可以在MaxScript中灵活使用.NET的文件操作功能,实现各种复杂的文件处理任务。
本文档涵盖了MaxScript与.NET集成的各个方面,从基础的UI控件到高级的动态编译和异步操作。通过这些示例,您可以:
最佳实践建议:
通过掌握这些技术,您将能够创建功能强大、性能优秀的MaxScript工具和插件。