Dotnet_for_max

3ds Max SDK 更新于 2026-11-09 content/docs 文件
目录(86)

# .NET for MaxScript - 集成指南

从PDF转换为优化Markdown格式

概述

本文档介绍了如何在3ds Max的MaxScript中使用.NET框架进行集成开发,包含各种UI控件、文件操作和数据处理示例。


1. 基础UI控件示例

1.1 按钮控件与拖拽功能

-- 创建测试对话框
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

1.2 文本框控件

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

功能说明:

  • 支持多行文本输入
  • 垂直滚动条
  • 支持回车和Tab键
  • 自动换行功能

2. 窗体应用程序

2.1 创建独立窗体

-- 创建文本框
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

3. 消息对话框

3.1 MessageBox枚举类型

/*
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)
*/

3.2 消息对话框示例

(
    -- 设置.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"
    )
)

4. 选项卡界面

4.1 多页界面实现

(
    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
)

5. 数据表格处理

5.1 数据网格与数据表

(
    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
)

6. 文件操作

6.1 文件时间比较

-- 获取文件信息
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旧

6.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"

6.3 文件选择对话框

-- 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
    -- 在这里处理文件数组...
)

7. 数组操作

7.1 .NET数组处理

-- .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)
)

8. 表格布局面板

8.1 表格布局示例

(
    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
)

相关资源


注意事项

  1. 索引从0开始:.NET数组和集合的索引从0开始,与MaxScript的1开始不同
  2. 类型转换:注意MaxScript类型与.NET类型的转换
  3. 内存管理:适当释放.NET对象以避免内存泄漏
  4. 异常处理:使用try-catch处理可能的.NET异常

9. 动态编译C#代码

9.1 基础动态编译

( 
    -- 加载必要的程序集 
    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())
        )
    ) 
)

9.2 动态编译带UI的窗体

( 
    -- 定义包含窗体的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() 
    ) 
)

9.3 动态编译自定义控件

( 
    -- 定义自定义控件 
    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 
    ) 
)

10. 高级UI控件

10.1 TreeView树形控件

(
    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
)

10.2 ListView列表视图

(
    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
)

10.3 ProgressBar进度条

( 
    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 
)

11. 文件系统操作

11.1 目录遍历

( 
    -- 获取指定目录下的所有文件 
    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 
    ) 
)

11.2 文件复制和移动

(
    -- 复制文件
    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
    )
)

11.3 创建和删除目录

(
    -- 创建目录
    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
    )
)

12. 网络请求

12.1 HTTP GET请求

(
    -- 创建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()
)

12.2 HTTP POST请求

(
    -- 创建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()
)

13. 正则表达式

13.1 基础正则表达式

(
    -- 创建正则表达式(注意: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
    )
)

13.2 字符串替换

(
    -- 创建正则表达式
    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
)

13.3 验证格式

(
    -- 验证电子邮件格式
    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
        )
    )
)

14. 线程和异步操作

14.1 使用Timer定时器

(
    -- 创建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"
)

14.2 后台任务

(
    -- 创建后台工作线程
    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()
)

15. 数据序列化

15.1 JSON序列化

(
    -- 定义数据类
    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
    )
)

16. 系统信息获取

16.1 获取系统信息

(
    -- 获取计算机名称
    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)
)

16.2 获取环境变量

(
    -- 获取所有环境变量
    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
)

17. 事件和委托

17.1 自定义事件

(
    -- 定义带事件的类
    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()
    )
)

18. 图形绘制

18.1 使用Graphics绘制

(
    -- 创建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
)

19. 集合操作

19.1 List集合

(
    -- 创建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
    )
)

19.2 Dictionary字典

-- 创建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 "苹果")

20. 实用工具函数

20.1 文件编码转换

(
    -- 读取文件内容(指定编码)
    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"
    )
)

20.2 路径操作

(
    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
)

21. 性能优化技巧

21.1 使用StringBuilder

(
    -- 错误方式:字符串拼接
    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)
)

21.2 使用Stopwatch计时

(
    -- 创建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
)

22. 调试和日志

22.1 使用Debug输出

(
    -- 使用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 "打印信息"
)

22.2 使用Trace输出

(
    -- 使用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 "取消缩进的信息"
)

23. 异常处理最佳实践

23.1 捕获特定异常

(
    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
        )
    )
)

23.2 使用finally块

(
    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"
        )
    )
)

24. 扩展MaxScript功能

24.1 创建MaxScript包装器

-- 创建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())
        )
    )
)

25. 完整示例:场景导出工具

25.1 综合应用示例

-- 综合应用示例:场景导出工具
(
    -- 定义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())
        )
    )
)

26. 文件操作详细示例

本文档提供了在3ds Max MaxScript中使用.NET进行文件操作的详细示例。

26.1 目录

  1. 文件基本操作
  2. 文件信息获取
  3. 文件时间比较
  4. 文件复制和移动
  5. 文件内容读写
  6. 目录操作
  7. 路径操作
  8. 文件选择对话框

26.2 文件基本操作

26.2.1 检查文件是否存在

-- 检查文件是否存在
(
    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
)

26.2.2 创建文件

-- 创建新文件
(
    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
)

26.2.3 删除文件

-- 删除文件
(
    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
    )
)

26.3 文件信息获取

26.3.1 获取文件详细信息

-- 获取文件信息
(
    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
)

26.3.2 获取文件目录信息

-- 获取文件所在目录
(
    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
)

26.4 文件时间比较

26.4.1 比较两个文件的修改时间

-- 比较两个文件的修改时间
(
    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
)

26.4.2 检查文件是否在指定时间之后修改

-- 检查文件是否在指定时间之后修改
(
    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"
)

26.5 文件复制和移动

26.5.1 复制文件

-- 复制文件
(
    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
)

26.5.2 移动文件

-- 移动文件
(
    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
)

26.6 文件内容读写

26.6.1 读取文件内容

-- 读取文件内容
(
    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
    )
)

26.6.2 写入文件内容

-- 写入文件内容
(
    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
)

26.6.3 追加文件内容

-- 追加文件内容
(
    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
)

26.7 目录操作

26.7.1 创建目录

-- 创建目录
(
    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
    )
)

26.7.2 删除目录

-- 删除目录
(
    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
    )
)

26.7.3 目录遍历

-- 遍历目录中的文件和子目录
(
    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
    )
)

26.8 路径操作

26.8.1 路径组合

-- 组合路径
(
    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
)

26.8.2 路径信息提取

-- 提取路径信息
(
    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)
)

26.8.3 临时路径操作

-- 获取临时路径
(
    local paths = dotNetClass "System.IO.Path"

    format "临时目录: %\n" (paths.GetTempPath())
    format "随机文件名: %\n" (paths.GetRandomFileName())
    format "临时文件名: %\n" (paths.GetTempFileName())
)

26.9 文件选择对话框

26.9.1 打开文件对话框

-- 文件选择对话框
(
    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
        )
    )
)

26.9.2 保存文件对话框

-- 保存文件对话框
(
    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
    )
)

26.10 示例脚本

以下是一个完整的示例脚本,演示了上述所有文件操作:

-- 文件操作完整示例
(
-- 定义测试文件路径
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"
)

26.11 注意事项

  1. 路径分隔符:在MaxScript中使用路径时,需要使用双反斜杠(\\)作为路径分隔符。
  2. 编码处理:读取和写入文件时,建议指定编码格式,以避免中文等特殊字符出现乱码。
  3. 异常处理:文件操作可能会遇到各种异常(如文件被占用、权限不足等),建议使用try-catch语句进行异常处理。
  4. 资源释放:对于使用Stream等需要手动释放资源的操作,要确保在使用完毕后调用Dispose()方法释放资源。
  5. 跨平台兼容性:如果脚本需要在不同操作系统上运行,建议使用System.IO.Path类的方法来处理路径,而不是硬编码路径分隔符。

通过以上示例,你可以在MaxScript中灵活使用.NET的文件操作功能,实现各种复杂的文件处理任务。


总结

本文档涵盖了MaxScript与.NET集成的各个方面,从基础的UI控件到高级的动态编译和异步操作。通过这些示例,您可以:

  1. 扩展MaxScript功能:利用.NET丰富的类库增强MaxScript能力
  2. 创建专业UI:使用Windows.Forms构建复杂用户界面
  3. 动态编译代码:运行时编译和执行C#代码
  4. 处理数据:使用集合、序列化等技术管理数据
  5. 系统集成:访问文件系统、网络、系统信息等
  6. 优化性能:使用StringBuilder、Stopwatch等工具提升效率

最佳实践建议:

  • 优先使用.NET内置类库,避免重复造轮子
  • 注意MaxScript和.NET之间的类型转换
  • 合理使用try-catch处理异常
  • 及时释放.NET对象避免内存泄漏
  • 使用动态编译实现复杂逻辑,提高代码可维护性

通过掌握这些技术,您将能够创建功能强大、性能优秀的MaxScript工具和插件。