【问题标题】:C# : File rename using ASP:NET MVC and IISExpressC#:使用 ASP:NET MVC 和 IISExpress 重命名文件
【发布时间】:2020-01-21 22:12:00
【问题描述】:

我有一个实用程序可以使用特定条件重命名指定目录中的文件。使用控制台应用程序运行代码效果很好,并且文件被适当地重命名。但是,当我在 Web 应用程序中尝试相同的操作时,文件不会被重命名。我正在使用 VS2017 开发服务器进行 Web 应用程序调试。

我错过了什么?

使用如下控制台应用程序代码成功重命名文件:

重命名方法:

public static string AddSuffix(string filename, string suffix)
{
    string fDir = Path.GetDirectoryName(filename);
    string fName = Path.GetFileNameWithoutExtension(filename);
    string fExt = Path.GetExtension(filename);
    string renamedFilePath = Path.Combine(fDir, String.Concat(fName, suffix, fExt));
    return renamedFilePath;
}

在主程序中的使用:

static void Main(string[] args)
{
    string batchperiod = "_70_";
    string realPath = @"C:\Users\myuser\source\repos\Solution\Project\BatchIn";
    IEnumerable<string> fileList = Directory.EnumerateFiles(realPath);

    var CurrentBatchName = (from file in fileList
                            let fileName = Path.GetFileName(file)
                            where fileName.Contains(batchperiod)
                            select fileName).FirstOrDefault();

    string absolutePath = (@"C:\Users\myuser\source\repos\Solution\Project\BatchIn\" + CurrentBatchName);
    string newPath = Helpers.AddSuffix(absolutePath, String.Format("({0})", Helpers.parameters.IsProcessed));

    System.IO.FileInfo fi = new System.IO.FileInfo(absolutePath);

    if (fi.Exists)
    {
        fi.MoveTo(newPath);
    }
}

使用此代码,文件已成功重命名为

GL_Export_70_201907081058.xml

GL_Export_70_201907081058(P).xml

使用 Web 应用程序的唯一区别是 absolutePath 存储在 Session 变量中......它派生自前面的操作/ActionResult:

var absolutePath = (@"C:\Users\myuser\source\repos\Solution\Project\BatchIn\" + CurrentBatchName);
files.FileName = CurrentBatchName;
Session["AbsoluteBatchPath"] = absolutePath;

后来在另一个 ActionResult 中调用为:

var sourceFile = Convert.ToString(Session["AbsoluteBatchPath"]);
string newPath = AddSuffix(sourceFile, String.Format("({0})", parameters.IsProcessed));
System.IO.FileInfo fi = new System.IO.FileInfo(sourceFile);

if (fi.Exists)
{
    // Move file with a new name. Hence renamed. 
    fi.MoveTo(newPath);
}

我错过了什么?

我怀疑在尝试使用 Visual Studio 开发服务器重命名时可能需要配置一些权限。

【问题讨论】:

  • 您是否从网络应用程序中收到任何错误?这看起来像是权限相关问题,请检查您运行 Web 应用程序的用户的文件夹权限。

标签: c# asp.net-mvc file file-io


【解决方案1】:

您的代码完美无缺,调试并检查您的代码是否在 MVC 中输入了 fi.exist if 条件..

请确认一下

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-30
    • 2014-09-09
    • 2016-05-29
    • 2014-04-27
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 2016-06-06
    相关资源
    最近更新 更多