0
I took a project from a Filemanager, which uses Handler and the same uses examples listing the directories and files of the project itself, put an example listing directory that already works, but I can’t do the same for file:
namespace Filemanager
{
/// <summary>
/// Summary description for FilemanagerHandler
/// </summary>
public class FilemanagerHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
var opName = context.Request.Params["opName"];
List<FileItem> retList = new List<FileItem>();
short i;
switch (opName)
{
case "getDirs":
var dir = context.Request.QueryString["dir"];
//lista diretorios Raiz
var listaDir = DiretorioController.getAllDirectory("");
foreach (var diretorio in listaDir)
{
retList.Add(new FileItem(diretorio.nomeDiretorio));
}
break;
case "getFiles":
dir = context.Request.QueryString["dir"];
foreach (var address in Directory.GetFiles(context.Server.MapPath(dir)))
{
retList.Add(new FileItem(address));
}
break;
case "uplaodFile":
dir = context.Request.Params["dir"];
//HttpPostedFile file = context.Request.Files["fileUpload"];
foreach (string key in context.Request.Files.AllKeys)
{
HttpPostedFile file = context.Request.Files[key];
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string address = context.Server.MapPath(Path.Combine(dir, fileName));
i = 1;
while (File.Exists(address))
{
address = context.Server.MapPath(Path.Combine(dir, Path.GetFileNameWithoutExtension(fileName) + " (" + i++ + ")" + Path.GetExtension(fileName)));
}
file.SaveAs(address);
}
}
break;
case "addFolder":
dir = context.Request.Params["dir"];
Directory.CreateDirectory(context.Server.MapPath(Path.Combine(dir, context.Request.Params["folderName"].ToString())));
context.Response.Redirect(context.Request.UrlReferrer.ToString());
break;
case "addFile":
dir = context.Request.Params["dir"];
var filename = context.Request.Params["fileName"].ToString();
filename = string.IsNullOrEmpty(Path.GetExtension(filename)) ? filename + ".txt" : filename;
StreamWriter streamWriter = File.CreateText(context.Server.MapPath(Path.Combine(dir, filename)));
streamWriter.Close();
break;
case "dlFile":
dir = context.Request.Params["dir"];
context.Response.ContentType = "application/octet-stream";
filename = context.Server.MapPath(dir);
context.Response.WriteFile(filename);
context.Response.Headers.Add("Content-Disposition", "attachment;filename=" + Path.GetFileName(filename));
return;
break;
case "copy":
var dir1 = context.Request.Params["dir1"];
var dir2 = context.Request.Params["dir2"];
var addressTocopy = context.Server.MapPath(Path.Combine(dir1, Path.GetFileName(dir2)));
i = 1;
while (File.Exists(addressTocopy))
{
addressTocopy =
context.Server.MapPath(Path.Combine(dir1,
Path.GetFileNameWithoutExtension(dir2) + " (" +
i + ")" + Path.GetExtension(dir2)));
}
File.Copy(context.Server.MapPath(dir2), addressTocopy);
break;
case "cut":
dir1 = context.Request.Params["dir1"];
dir2 = context.Request.Params["dir2"];
addressTocopy = context.Server.MapPath(Path.Combine(dir1, Path.GetFileName(dir2)));
i = 1;
while (File.Exists(addressTocopy))
{
addressTocopy =
context.Server.MapPath(Path.Combine(dir1,
Path.GetFileNameWithoutExtension(dir2) + " (" +
i + ")" + Path.GetExtension(dir2)));
}
File.Move(context.Server.MapPath(dir2), addressTocopy);
break;
case "delete":
dir = context.Request.Params["dir"];
string deleteAdd = context.Server.MapPath(dir);
if (File.Exists(deleteAdd))
{
File.Delete(deleteAdd);
}
else
{
if (Directory.Exists(deleteAdd))
Directory.Delete(deleteAdd);
}
break;
case "rename":
dir = context.Server.MapPath(context.Request.Params["dir"]);
var rename = context.Request.Params["name"];
if (File.Exists(dir))
{
var renameAdd = string.IsNullOrEmpty(Path.GetExtension(rename))
? Path.Combine(Path.GetDirectoryName(dir),
rename + Path.GetExtension(dir))
: Path.Combine(Path.GetDirectoryName(dir), rename);
File.Move(dir, renameAdd);
retList.Add(new FileItem(renameAdd));
}
else if (Directory.Exists(dir))
{
var renameAdd = Path.Combine(dir.Remove(dir.LastIndexOf('\\') + 1), rename);
Directory.Move(dir, renameAdd);
retList.Add(new FileItem(renameAdd));
}
break;
default:
break;
}
if (context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
context.Response.Write(JsonConvert.SerializeObject(retList));
else
context.Response.Redirect(context.Request.UrlReferrer.ToString());
}
catch (Exception)
{
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Listitem class:
namespace Filemanager.Classes
{
public class FileItem
{
private string _address;
private FileInfo fileInfo;
public string Title { get { return Address.ToCharArray().Contains('/') ? Address.Remove(0, Address.LastIndexOf('/')).TrimStart('/') : Address; } }
public FileItem(string address)
{
_address = address;
fileInfo = new FileInfo(_address);
}
public string Address
{
get { return _address.Replace(HttpContext.Current.Server.MapPath("/"), "").Replace("\\", "/"); }
set { _address = value; }
}
public string Extension
{
get
{
try
{
var ext = Path.GetExtension(Address);
return string.IsNullOrEmpty(ext) ? "folder" : ext.TrimStart('.');
}
catch (Exception)
{
return "";
}
}
}
public string Category { get { return GetCategory(Extension); } }
public long FileSize { get { return Category.ToLower() == "folder" ? 0 : fileInfo.Length; } }
public DateTime DateCreated { get { return fileInfo.CreationTime; } }
protected string GetCategory(string extension)
{
string[] imageTypes = { ".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".gif" };
string[] programTypes = { ".html", ".cs", ".js", ".css", ".aspx", ".ashx", ".config" };
if (Extension.Equals("folder", StringComparison.InvariantCultureIgnoreCase) || string.IsNullOrEmpty(Extension))
{
return "Folder";
}
else if (imageTypes.Contains(extension.ToLower()))
{
return "Image";
}
else if (programTypes.Contains(extension.ToLowerInvariant()))
{
return "Code";
}
return "Unknown";
}
}
} However there works with local directories, what I have to change so much to list from my database? I already have all dal methods ready and working.
Project reference: https://github.com/danielrajaei/Filemanager/tree/master/Filemanager
What is the access technology to your database? Could you give an example of simple selection in your question?
– Leonel Sanches da Silva
@Ciganomorrisonmendez is Entity framework, I have a method that returns a list of directories, I changed the foreach there for my list, and listed the directories, however I went to do the same in the files and was not. file not found. is as if the Fileitem class is static for a file directory. I edited the question with the example of my selection method.
– War Lock
What mistake do you have with the
FileItem
? Apparently the problem you have is different from the general idea of the question.– Leonel Sanches da Silva
I haven’t been able to adapt anything yet,if I put the same foreach I did in directories, switching to my file method in case:"getFiles" appears: Could not find the file 'Chrysanthemum.jpg'. this file is one of the data registered in the bd, this error is because the Fileitem class is pulling a static location? I have to set it to the folder where will be saved the files? I am in doubt of the context, I do not want to do all these methods there, I just wanted to leave the list of directories/ files working.
– War Lock
I think it is a problem in the construction of Path. Apparently you are using a relative path. Try a test using
Path.Join
andServer.MapPath
. If need be, I’ll put an answer to you using these two resources.– Leonel Sanches da Silva
I don’t understand, I have to put this where?
– War Lock
Let’s go continue this discussion in chat.
– War Lock
Strange that just with my method of getting it files from error, I repeated in the same location my method of getting directories, and list normally, both return names(string). I do not understand why the files it of error.
– War Lock
@Ciganomorrisonmendez vai chat pf.
– War Lock