希望有人可以在这里为我提供帮助,我对使用目录不是很熟悉。我的应用程序压缩文件并将其存储在媒体目录中,以及将它们存储在数据库中。如果我创建目录并实际分别调用每个文件,则此方法效果很好。
但是我想使其动态化,并处理install文件夹下的所有文件夹,对于该目录下的每个目录,我想处理该目录下的每个目录和所有文件。
我尝试过的事情:
public class SetupFiles : ISetupFiles
{
private readonly ISession _session;
private readonly IFileService _fileService;
private readonly IFileProvider _fileProvider;
public SetupFiles(ISession session, IFileService fileService, IFileProvider fileProvider)
{
_session = session;
_fileService = fileService;
_fileProvider = fileProvider;
}
public void Setup()
{
string installPath = ("install/images/");
_session.Transact(session =>
{
DirectoryInfo dir = new DirectoryInfo(installPath);
DirectoryInfo[] subdirectories = dir.GetDirectories();
foreach (var subdirectory in subdirectories)
{
string currentDirName = Directory.GetCurrentDirectory();
var directory = new MediaCategory
{
Name = subdirectory.Name.ToString().ToUpper(),
UrlSegment = subdirectory.Name.Trim().ToLower(),
};
session.Save(directory);
string[] pngFiles = Directory.GetFiles(currentDirName, "*.png", SearchOption.AllDirectories);
string[] jpgFiles = Directory.GetFiles(currentDirName, "*.jpg", SearchOption.AllDirectories);
string[] gifFiles = Directory.GetFiles(currentDirName, "*.gif", SearchOption.AllDirectories);
string[] pdfFiles = Directory.GetFiles(currentDirName, "*.pdf", SearchOption.AllDirectories);
foreach (var currentPngFile in pngFiles)
{
var fileStream = _fileProvider.GetFileInfo(currentPngFile).CreateReadStream();
MediaFile dbpngFile = _fileService.AddFile(fileStream, Path.GetFileName(currentPngFile), "image/png", fileStream.Length, directory);
}
foreach (var currentJpgFile in jpgFiles)
{
var fileStream = _fileProvider.GetFileInfo(currentJpgFile).CreateReadStream();
MediaFile dbjpgFile = _fileService.AddFile(fileStream, Path.GetFileName(currentJpgFile), "image/jpg", fileStream.Length, directory);
}
foreach (var currentGifFile in gifFiles)
{
var fileStream = _fileProvider.GetFileInfo(currentGifFile).CreateReadStream();
MediaFile dbgifFile = _fileService.AddFile(fileStream, Path.GetFileName(currentGifFile), "image/gif", fileStream.Length, directory);
}
foreach (var currentPdfFile in pdfFiles)
{
var fileStream = _fileProvider.GetFileInfo(currentPdfFile).CreateReadStream();
MediaFile dbgifFile = _fileService.AddFile(fileStream, Path.GetFileName(currentPdfFile), "file/pdf", fileStream.Length, directory);
}
}
});
}
但是由于某种原因,我收到一个错误,它找不到目录。
任何帮助将不胜感激。
int行DirectoryInfo[] subdirectories = dir.GetDirectories();
的目录显示目录,但是GetDirectories()
返回NULL。
答案 0 :(得分:0)
我一定有脑筋。大声笑在@ ciubotariu-florin的帮助下,我得以解决了这个问题。
对于其他遇到此问题的人,wwwroot是一个环境文件夹,并且是IIS config中Web root的一部分。因此,要与Directory()
和/或DirectoryInfo()
一起使用,必须使用IHostingEnvironment
,这样才能使用IHostingEnvironment.WebRootPath
,以便更改我的路径
string installPath = ("install/images/");
到
string installPath = Path.Combine(_env.WebRootPath, "install/images/").ToLower();
解决了我的问题。