-2

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

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

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

3 回答 3

4

关于什么:

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

编辑:

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

if(filename.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
   bitmap.Save(@"C:\" + textBox4.Text + ".jpg");
else
   MessageBox.Show("Error: the file name contains invalid chars");
于 2012-08-05T18:57:54.727 回答
1

不要那样做,使用 SaveFileDialog 组件。它将处理路径、有效名称、提取特殊文件夹(如文档等)。

于 2012-08-05T19:06:44.270 回答
1

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

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
}
于 2012-08-05T19:14:07.350 回答