Directory.GetFiles Path Issue - c#

I Have always used Confid.VirtualDir for my paths. For example:
Config.VirtualDir + "upload/gallery/image.jpg"
This gives me the path of /upload/gallery/image.jpg. which works totally fine in every page for example:
<img style="height: 100px; " src="<%=Config.VirtualDir + "upload/gallery/image.jpg" %>" />
works perfectly fine.
BUT now I have problem with Directory.GetFiles.
It works on:
protected string[] images;
images = Directory.GetFiles(#"C:\website\mysite.com\upload\gallery", "*.jpg");
But not with:
protected string[] images;
string path = Config.VirtualDir + "upload/gallery";
images = Directory.GetFiles(path,"*.jpg");
I don't see any errors in console.
I also tried "upload\gallery" but i get error "Unrecognize escape sequence".
Using #"C:\website\mysite.com\upload\gallery", will expose directory structure of my server, which I'd rather to avoid.
UPDATE: Based on Alex K. advice. I tried:
protected string[] images;
protected string realImage;
string path = Server.MapPath(#"~\upload\Gallery");
images = Directory.GetFiles(path, "*.jpg");
realImage = Path.Combine(Server.MapPath(#"~\upload\Gallery"), Config.VirtualDir + "upload/Gallery");
Now I'm Confused how to use path to GetFiles and realImage path to get my images.
UPDATE2: Got it to work. Thanks Alex K. I Answer below

Description in comments:
Code File:
public List<string> images = new List<string>();
protected string realPath;
protected void Page_Load(object sender, EventArgs e)
{
string path = Server.MapPath(#"~\upload\Gallery");
// this gets the actual directory path.
realPath = Path.Combine(path, Config.VirtualDir + "upload/Gallery/");
//this changes the path to the VirtualDir path
DirectoryInfo di = new DirectoryInfo(path);
//this gets file names in the folder
foreach(var fi in di.GetFiles())
{
images.Add(fi.Name);
//adds file names to images list
}
}
HTML:
<img style="height: 100px; " src="<%=realPath + images[0]%>" />
//any images[i] is accessible

Related

System.IO.DirectoryNotFoundException: 'Could not find a part of the path

I'm trying to implement a method that return files from a folder of my computer, but, this error showed for me:
System.IO.DirectoryNotFoundException: Could not find a part of the path.
This is my code:
public List<string> GetFileName()
{
List<string> arquivos = new List<string>();
DirectoryInfo d = new DirectoryInfo("C:\\Files");
FileInfo[] Files = d.GetFiles();
foreach (FileInfo file in Files)
{
arquivos.Add(file.Name);
}
return arquivos;
}
I would like know if in .NET MAUI or Xamarin Forms this process for take a path external is different. Thank you since now!
I am afraid that your path is incorrect.So you are getting the error "Could not find a part of the path".
Could you please change the code like below?
private void Button_Clicked(object sender, EventArgs e)
{
List<string> arquivos = new List<string>();
DirectoryInfo d = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
FileInfo[] Files = d.GetFiles();
}
Also please be aware that Environment.SpecialFolder.LocalApplicationData maps to /data/user/0/com.companyname.mauiapptest/files locally in MAUI.
Reference link.

Path.Combine() C#

So on my previous question (C# Only File NAMES in ListBox) I asked how to show only the file names.I got that to work. Then I encountered another problem: I could not load whats in the directory because there is no way to. A user told me
"
You either need to use a Dictionary datasource for your ListBox (with the key being the file name and the value being that path) See this answer for an idea of what I mean. Or you need to rebuild the path in your
IndexChange function (using Path.Combine() )
"
And me being me, I had no clue what he meant. So I came back for more help. I have not put any code as I don't know how to.
https://msdn.microsoft.com/it-it/library/fyy7a5kt(v=vs.110).aspx
string folder = #"C:/Aatrox";
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var fileName = (string)ListBox1.SelectedItem;
textEditorControl1.Text = File.ReadAllText(Paht.Combine(folder, fileName));
}
private void FlatButton3_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] txtfiles = Directory.GetFiles(folder, "*.txt");
string[] luafiles = Directory.GetFiles(folder, "*.lua");
foreach (var item in txtfiles)
{
ListBox1.Items.Add(Path.GetFileName(item));
}
foreach (var item in luafiles)
{
ListBox1.Items.Add(Path.GetFileName(item));
}
}
If I understand correctly, you want a List of file names from a certain directory. You want to use Directory.EnumerateFiles to get each file in the directory. Path.Combine only combines a directories path, for modularity and use on other PC's mainly, such as Path.Combine(Environment.CurrentDirectory, "Hello").

Error Access to the path is denied when Rename a Directory

I want to rename the a folder with the new name inputed in a Textbox txtFilenFolderName:
protected void btnUpdate_Click(object sender, EventArgs e)
{
string[] values = EditValue;
string oldpath = values[0];// = "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder"
string oldName = values[2]; //= New Folder
string newName = txtFilenFolderName.Text; //= New Folder1
string newPath = string.Empty;
if (oldName != newName)
{
newPath = oldpath.Replace(oldName, newName);
Directory.Move(oldpath, newPath);
}
else
lblmessage2.Text = "New name must not be the same as the old ";
}
}
Try to debug:
oldpath = "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder"
oldName = New Folder
newName= New Folder1
newpath = "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder1"
Everything seems right, but I when I click on buton Edit ---> rename---> Update---> an error occur: Access to the path is denied D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder
Help!
the path "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder" probably doesn't exist. I'm thinking you meant "D:\C#Projects\website\Lecturer\giangvien\New folder". I think what #CharmingInferno was trying to get at was that when you use # in front of a string you don't need to use escape characters as it takes the text as is like the following
string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt
string h = #"\\server\share\file.txt"; // \\server\share\file.txt
However you are putting your values in the EditValue string array should be corrected.
I had the same problem just now.
Using
Directory.Move(srcDirectory, dstDirectory);
sometimes caused the Access to the path /dstDirectory/ is denied exception, sometimes it don't.
The following solved for me.
new DirectoryInfo(srcDirectory).MoveTo(dstDirectory);

how to save files in a folder in asp.net- error in path name

protected void Button1_Click(object sender, EventArgs e)
{
FileUpload1.SaveAs(Server.MapPath("blablabla//" + FileUpload1.FileName));
}
This is the code behind my button for uploading a file to a folder in my web application in ASP.NET
But im getting an error that says DirectoryNotFoundException was unhandled by user code.
How can i solve this error? The problem is the path name that leads to my folder called "blablabla",
I want to save files in this folder using a FileUpload control.
Any help would be greatly appreciated.
Because you should specify the destination path starting from the root folder of your site.
Also there is no need to dupe the forward slash
FileUpload1.SaveAs(Server.MapPath("/blablabla/" + FileUpload1.FileName));
Try this ....
protected void Button1_Click(object sender, EventArgs e)
{
string Img_name = FileUpload1.FileName;
string folder_path = Server.MapPath("~\\userimages\\");
FileUpload1.SaveAs(folder_path + Img_name);
}
Try this,
string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string Path = Server.MapPath("/" + filename);
FileUpload1.SaveAs(Path);

C# code to copy files, can this snippet be improved?

While copying around 50 GB of data via local LAN share, due to connectivity issue copy failed at around 10 GB copied.
I have renamed copied 10GB of data directory to localRepository and then written a C# program to copy files from the remote server to destination, only if it is not found in local repository. If found move file from local repository to destination folder.
Although the code worked fine and accomplishes the task very well. I wonder, have I written the most efficient code? Can you find any improvements?
string destinationFolder = #"C:\DataFolder";
string remoteRepository = #"\\RemoteComputer\DataFolder";
string localRepository = #"\\LocalComputer\LocalRepository";
protected void Page_Load(object sender, EventArgs e)
{
foreach (string remoteSrcFile in Directory.EnumerateFiles(remoteRepository, "*.*", SearchOption.AllDirectories))
{
bool foundInLocalRepo = false; ;
foreach (var localSrcFile in Directory.EnumerateFiles(localRepository, "*.*", SearchOption.AllDirectories))
{
if (Path.GetFileName(remoteSrcFile).Equals(Path.GetFileName(localSrcFile)))
{
FileInfo localFile = new FileInfo(localSrcFile);
FileInfo remoteFile = new FileInfo(remoteSrcFile);
//copy this file from local repository
if (localFile.Length == remoteFile.Length)
{
try
{
File.Move(localSrcFile, PrepareDestinationPath(remoteSrcFile));
Debug.WriteLine(remoteSrcFile + " moved from local repo");
}
catch (Exception ex)
{
Debug.WriteLine(remoteSrcFile + " did not move");
}
foundInLocalRepo = true;
break;
}
}
}
if (!foundInLocalRepo)
{
//copy this file from remote repository
try
{
File.Copy(remoteSrcFile, PrepareDestinationPath(remoteSrcFile), false);
Debug.WriteLine(remoteSrcFile + " copied from remote repo");
}
catch (Exception ex)
{
Debug.WriteLine(remoteSrcFile + " did not copy");
}
}
}
}
private string PrepareDestinationPath(string remoteSrcFile)
{
string relativePath = remoteSrcFile.Split(new string[] { "DataFolder" }, StringSplitOptions.None)[1];
string copyPath = Path.GetFullPath(destinationFolder + relativePath);
Directory.CreateDirectory(Path.GetDirectoryName(copyPath));
return copyPath;
}
EDIT:
Based on answer given by Thomas I am attempting to zip the file.
Traditionally as an end user we use to zip a file and then copy. As a programmer can we zip and copy the file parallel? I mean the portion which has been zipped send it over the wire?
You are doing far too much work with the nested loop.
You should remove the inner "foreach" and replace it with some code that:
(1) Constructs the name of the file that you are looking for and
(2) Uses File.Exists() to see if exists, then
(3) Continues with the same block of code that you currently have following the "if (Path.GetFileName(remoteSrcFile)..." condition.
Something like this:
foreach (string remoteSrcFile in Directory.EnumerateFiles(remoteRepository, "*.*", SearchOption.AllDirectories))
{
string localSrcFile = Path.Combine(localRepository, Path.GetFileName(remoteSrcFile));
if (File.Exists(localSrcFile))
{
...
}
}
I would suggest zipping the files before moving. Try take a look at the very simple http://dotnetzip.codeplex.com/
Try zipping 1000 files a time, in that way, you don't have to run the for-loop that many times and establish new connections etc each time.

Categories

Resources