开发者

MVC C# Fnding file on server corresponding to name if condition

开发者 https://www.devze.com 2023-02-03 09:29 出处:网络
trying to get to grips with the code of a system that has been passed on to me. It has been written in asp.net C# MVC.

trying to get to grips with the code of a system that has been passed on to me. It has been written in asp.net C# MVC.

One section of this system locates files in a folder on the server, and imports them to a database. The details for the files are kept in an excel file which is also in the same folder on the server.

Currently in the excel sheet, if there is a value under the column PDFName, the system will look for a file corresponding to that name. If there is no matching file, the system will not import the data.

What I need to do, it change it so that if there is a file, it will import the file with it's data, however if there is not a file, it will import the data so that just the file can be added at a later date. Below is the snippet from the code where it looks for the corresponding file.

        if (!string.IsNullOrEmpty(fileRow.PDFName))
        {
            try
            {
                FileInfo matchingFile = files.First(df => (df.Extension.ToLower() == ".pdf" && df.Name.Replace(df.Extension, "").ToLower() == fileRow.PDFName));

                FTPFileEntry f = new FTPFileEntry()
                {
                    FileExtension = matchingFile.Extension,
                    FileName = matchingFile.Name,
                    Name = titleRow.PDFName,
                    Type = matchingFile.Extension.Trim('.')
                };

开发者_如何学运维                fileRow.FileEntry.Add(f);
            }
            catch (InvalidOperationException)
            {

            }
        }

I'm just a bit unsure as to how to go about building in the condition if there is no matching file, do something else. I was thinking something like:

if (!string.IsNullOrEmpty(fileRow.PDFName))
        { 


            FileInfo matchingFile = files.First(df => (df.Extension.ToLower() == ".pdf" && df.Name.Replace(df.Extension, "").ToLower() == fileRow.PDFName));


            if (matchingFile != null)
            {
                FTPFileEntry f = new FTPFileEntry()
                {
                    FileExtension = matchingFile.Extension,
                    FileName = matchingFile.Name,
                    Name = titleRow.PDFName,
                    Type = matchingFile.Extension.Trim('.')
                };

                fileRow.FileEntry.Add(f);

            }
            else
            {
                //Add data to database
            }
        }

I was just wondering if I'm going in the right direction with this? Any pointers would be appreciated :)


It looks fine to me. You could also use the first snippet of code and add data to the database in the catch section, but catching the exception would reduce the performances (not by much, but nonetheless...)

0

精彩评论

暂无评论...
验证码 换一张
取 消