How can i get all files without file extension into an array - asp.net

How can i get all files without file extension into an array. I will supply the folder path.
Is this possible using Directory.GetFiles() or DirectoryInfo.GetFiles()?? Is there any alternative way?
I am using ASP.NET C#.

I would guess:
string[] files = Directory.GetFiles(dir,"*.")
(now verified; that works fine) - note that you may need to use Server.MapPath to switch between relative site paths and physical disk paths, and that the results of Directory.GetFiles are full paths.

If you need to get just the name part of all files in a folder (even those with extensions):
string[] files = Directory.GetFiles(dir,"*.*")
.Select(n => Path.GetFileNameWithoutExtension(n))
.ToArray();

Related

how to get the list of the images from the Application Directory

I am Developing a Web site and i need to read all the images from the images folder in the
application directory and i have to display all the images on the page can any body tell me how to read all the images from the images folder which is in my application directory.
Thanks in Advance.
This could help
https://web.archive.org/web/20210304125318/https://www.4guysfromrolla.com/articles/052803-1.aspx
To add to the answer of Mr. Disappointment, you can get a list of all the files using the command specified,
To get the path of the application using Server.MapPath.
Then getting the list of files, you can simply iterate and filter on the extensions you need.
This will get you an array of the file names in a given path:
string[] fileNames = System.IO.Directory.GetFiles(yourPath);
You can then generate URLs for them and use <img> tags written out to the response, for example something like ought to get the valid URLs:
string relativePath = Request.AppRelativeCurrentExecutionFilePath;
relativePath = relativePath.Substring(0, relativePath.LastIndexOf('/') + 1);
string requestPath = Path.GetDirectoryName(Server.MapPath(relativePath));
string[] fileNames = Directory.GetFiles(requestPath);
List<string> imageUrls = new List<string>(fileNames.Length);
foreach(var fileName in fileNames)
{
imageUrls.Add(Path.Combine(relativePath, Path.GetFileName(fileName)));
}
You could just write out the <img> items in the loop. Also, note that a call to GetFiles supplying only a path will return all available files so you might want to supply a searchPattern argument such as *.jpg.

How can I rename a file in ASP.NET?

In my project I want to rename the file before it is updating. For example a file in my system like Mycontact.xls. I want to rename it as sasi.xls (it is an excel file). How can I write the code in ASP.NET?
Actually I am using a fileupload control to get the file in and rename the file and upload the renamed file in a folder which is in Solution Explorer.
You can do it with the File.Move method eg:
string oldFileName = "MyOldFile.txt";
string newFileName = "MyNewFile.txt";
File.Move(oldFileName, newFileName);
C# does not provide a file rename function, unfortunately. Anyhow, the idea is to do this:
File.Copy(oldFileName, NewFileName);
File.Delete(oldFileName);
You can also use - File.Move.
Be aware that when that code executes, the owner of the file will turn into the identity you have set on your Application Pool on which the website is running.
That account might not have enough permissions to 'create new' or 'delete' files.
I would advise you to place all read/writable files in a seperate location so you can control the security settings seperately on that part. This will also split off the 'only readable files/executables' (like the aspx and such) from the 'read/writable' files.

ASP.NET localized files

I've got a web page with a link, and the link is suppose to correspond to a PDF is the given user's language. I'm wondering where I should put these PDF files though. If I put them in App_LocalResources, I can't specify a link to /App_LocalResources/TOS_en-US.pdf can I?
The PDF should definitely not be in the App_LocalResources folder. That folder is only for RESX files.
The PDF files can go anywhere else in your app. For example, a great place to put them would be in a ~/PDF folder. Then your links will have to be dynamically generated (similar to what Greg has shown):
string cultureSpecificFileName = String.Format("TOS_{0}.pdf", CultureInfo.CurrentCulture.Name);
However, there are some other things to consider:
You need a way to ensure that you actually have a PDF for the given language. If someone shows up at your site and has their culture specified as Klingon, it's unlikely that you have such a PDF.
You need to decide exactly what the file format will be. In the example given, the file would have to be named TOS_en-US.pdf. It you want to use the 2-letter ISO culture names, use CurrentCulture.TwoLetterISOLanguageName and then the file name would be TOS_en.pdf.
I would store the filename somewhere with an argument in it (i.e. "TOS_{0}.pdf" ) and then just add the appropriate suffix in code:
string cultureSpecificFileName = string.Format("TOS_{0}.pdf", CultureInfo.CurrentCulture);
Does the PDF have to have the same file name for each of the different languages? If not, put them all into a directory and just store the path in your resources file.

Rewrite urls from user submitted HTML

I use one WYSIWYG editor in a small cms. It allows users to upload files, images, etc. If I add image named dog.jpg, in source I'll get:
<img src="/myweb/userfiles/images/dog.jpg" />
I can save this to a database and use it later on any page, until I move my site to a live domain.
myweb is virtual directory in IIS. "/" points to root, in this case localhost, so I have to use "/myweb". However when I upload site to server and copy database there, all links will be broken, because there is no "myweb" folder on server.
My idea was to replace "/myweb" on save with empty string. I also have to replace full url, which editor creates for some files. On display I would have to add correct Application dir. I would probably save both versions in database, and only on server change force display version to update.
By now I've come up with:
p = p.Replace("href=\"" + fullUrl, "href=\"").Replace("src=\"" + fullUrl, "src=\"").Replace("href=\"" + partialUrl, "href=\"").Replace("src=\"" + partialUrl, "src=\"");
Which is ugly, hard to maintain and inefficient. I guess better approach would be to use regex, but I don't know how to do it.
My question is, can anyone recommend good article, blog/forum post on this? If you have other solution, great.
I am unsure the regex version has any of the characteristics you mention in this case.
That said, you can do:
string ReplaceUrlPaths(string html, string partialPath, string fullPath)
{
var pattern = string.Format("((href|src)=\")({0}|{1})", partialPath, fullPath);
var regex = new Regex(pattern);
return regex.Replace(html, m => m.Groups[1].Value);
}
[TestMethod]
public void TestMethod10()
{
var input = #"<img src=""/myweb/userfiles/images/dog.jpg"" />";
//carefull with any special regex char in the paths
var replaced = ReplaceUrlPaths(input, "/myweb", "/some/full/path");
Assert.AreEqual(
#"<img src=""/userfiles/images/dog.jpg"" />",
replaced);
}
If you are proceeding with that, refactor it to instantiate the regex once with the compile option(as the partialPath and fullPath won't be changing).
Also consider avoiding it all, by defining a web site with an alternate port to just have it as a root Url.
Store the local root path separately from the images. For each image, store the relative path to that image.
When displaying images locally, use the local root merged with the relative path. When you publish to the remote server, you add the remote root to the relative path.
Does your WYSIWYG editor allow you to configure the base URL e.g. so that paths to images can use relative paths? I think the FCKEditor has something like FCKConfig.BaseHref in it's config file that does something like this.
Alternatively can you run the site as a root site using the ASP.NET 2.0 web server? Then you wouldn't have to worry about rewriting paths to images as you could just use paths from the webroot.

What is the most efficient way to perform the reverse of Server.MapPath in an ASP.Net Application

I am building an MVC application in which I am reading a list of files from the file system and I want to pass the relative URL to that file to the view, preferably prefixed with "~/" so that whatever view is selected cab render the URL appropriately.
To do this, I need to enumerate the files in the file system and convert their physical paths back to relative URLs. There are a few algorithms I've experimented with, but I am concerned about efficiency and minimal string operations. Also, I believe there's nothing in the .Net Framework that can perform this operation, but is there something in the latest MVC release that can?
At the moment I don't know any built-in method to do it, but it's not difficult, I do it like this:
We need to get the Application root, and replace it in our new path with ~
We need to convert the backslashes to slashes
public string ReverseMapPath(string path)
{
string appPath = HttpContext.Current.Server.MapPath("~");
string res = string.Format("~{0}", path.Replace(appPath, "").Replace("\\", "/"));
return res;
}
Isn't this what UrlHelper.Content method does? http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.content.aspx
I did some digging, trying to get the UrlHelper class to work outside of a controller, then I remembered a old trick to do the same thing within an aspx page:
string ResolveUrl(string pathWithTilde)
Hope this helps!
See:
https://msdn.microsoft.com/en-us/library/system.web.ui.control.resolveurl(v=vs.110).aspx

Resources