如何将保存的位图文件命名为文本框的内容

本文关键字:文本 命名为 位图 保存 文件 | 更新日期: 2024-10-29 23:03:52

我的应用程序需要使用文本框中提供的文件名保存 JPEG 图像文件。我不想使用 SaveFileDialog,因为我不希望用户看到对话框或能够更改保存图像的位置。

如何从文本框设置已保存文件的名称?

private void button1_Click(object sender, EventArgs e)
{
    if (textBox4.Text.Length >= 1)
       bitmap.Save(@"C:'Test.jpg");
}

如何将保存的位图文件命名为文本框的内容

怎么样:

if(filename.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
   bitmap.Save(textBox4.Text);
else
   MessageBox.Show("Error: the file name contains invalid chars");

编辑:

那行不通。因为它必须将文件保存到 C: 和文件 必须是 JPG 图像,就像我的代码一样。我知道如何解决这个问题 保存文件对话框,但我不想看到任何保存文件的对话框和 用户不得更改我要保存的位置。

if(filename.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
   bitmap.Save(@"C:'" + textBox4.Text + ".jpg");
else
   MessageBox.Show("Error: the file name contains invalid chars");

不要这样做,请使用 SaveFileDialog 组件。它将处理路径,有效名称,拾取文档等特殊文件夹。

使用用户输入的文本时,应从字符串中删除任何非法字符,否则在尝试创建具有该名称的文件时将出现异常。

private static string RemoveInvalidChars(string s, char[] invalidChars) {
    foreach (char ch in invalidChars) {
        s = s.Replace(ch.ToString(), "");
    }
    return s.Trim();
}

使用此帮助程序方法,可以像这样保存位图

string path = RemoveInvalidChars(Path.GetDirectoryName(textBox4.Text),
                                 Path.GetInvalidPathChars());
string filename = RemoveInvalidChars(Path.GetFileName(textBox4.Text),
                                     Path.GetInvalidFileNameChars());
if (filename.Length > 0) {
    if (path.Length > 0) {
        filename = Path.Combine(path, filename);
    }
    bitmap.Save(filename);
} else {
    // not a valid filename
}