首页 > 解决方案 > OFD 的文件路径不适用于 TagLib

问题描述

我想在单击按钮后通过打开文件对话框选择一个 mp3 文件并将文件名更改为已指定的字符串。问题是当我将文件路径TagLib.File.Create()作为变量插入时,我得到一个 FileNotFound 异常。这是代码:

public partial class Form1 : Form
{
    OpenFileDialog ofd = new OpenFileDialog();

    string location = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ofd.ShowDialog();
        location = ofd.SafeFileName;
        var target = TagLib.File.Create(location);

        target.Tag.Title = "it works";
        target.Save();
    }
}

标签: c#taglib

解决方案


尝试使用

 location = ofd.FileName;

获取完整的文件路径,而不是

location = ofd.SafeFileName;

它给你文件名。

最佳做法也是:

TagLib.File target = null;
        if (!string.IsNullOrEmpty(location) && File.Exists(location))
        {
             target = TagLib.File.Create(location);
        }
        else
        {
            //log or print a warning 
        }

推荐阅读