如何搜索文件扩展名(.xls)并更改其名称? C#

时间:2018-10-05 17:59:15

标签: c# windows

我使用的产品是Beijer HMI,目前我可以生成报告并将其保存到已知位置(我的桌面-C:\ Users \ mrdav \ Desktop)。

我需要能够在桌面上搜索文件扩展名.xls并更改其名称。

由HMI生成报告时,它使用日期和时间,这意味着在生成文件时,名称每次都会不同。

按一下按钮,我需要在桌面上搜索.xls文件并将其名称更改为变量。

//这是我程序中的变量

string NewName = Globals.Tags.Tag1.Value;

生成的代码需要放在下面的示例中。

public partial class Screen1
{

    void Button1_Click(System.Object sender, System.EventArgs e)
    {

        // Code to be added here... 
    }


}

希望有人可以提供帮助,我正在使用功能有限的Windows Compact框架。

任何问题,请让我知道。

预先感谢

戴夫

2 个答案:

答案 0 :(得分:2)

以下是您如何执行此操作的示例:

DirectoryInfo dir = new DirectoryInfo(sExportPath);
FileInfo[] Files = dir.GetFiles("*.csv"); 
foreach(FileInfo file in Files )
{
   // rename file
   System.IO.File.Move(file.FullName, GenerateNewFileName());
}
//elsewhere in the class
private string GenerateNewFileName()
{
    //here is where you implement creating or getting the filename that you want your file to be renamed to. An example might look like the below
    string serialNumber = GetSerialNumber(); //Get the serial number that you talked about in the question. I've made it a string, but it could be an int (it should be a string)
    return Path.ChangeExtension(serialNumber,".xls"); //to use path you will need a using statement at the top of your class file 'using System.IO'
}

答案 1 :(得分:1)

这似乎行得通...但是我知道它不那么整洁。

有什么建议吗?

感谢所有的帮助,最终到达了!

    void Button_Click(System.Object sender, System.EventArgs e)
    {
        try
        {
        // Location for new file
            string NewFileName = @"c:\users\mrdav\desktop\testfolder\";
        // Add varibale name to new file
            NewFileName += Globals.Tags.Tag1.Value;
        // add .xls extention to new file
            NewFileName += ".xls";
        //show new file name to check all ok
            MessageBox.Show (NewFileName);
        //search for .xls in known directory
            DirectoryInfo di = new DirectoryInfo(@"c:\users\mrdav\desktop");
            FileInfo[] Files = di.GetFiles("*.xls");
        // if files exist with .xls extention
            foreach(FileInfo file in Files )
            {
            // show full file name
                MessageBox.Show (file.FullName);
            //rename old file to new file name and move to new folder
                File.Move(file.FullName, NewFileName);
            }
        }
        catch (Exception ex)

        {
            MessageBox.Show (ex.ToString());
        }
    }