C# simple class to convert a URL into acceptable windows file name
Posted: November 7, 2009 Filed under: C#.net | Tags: A simple C# class, Create file names from URL, Get word from url, Regular expression to access words from URL, remove special characters from URL Leave a comment »Hi, i was working on a project that takes screen-shots of web pages that are loaded in to Internet Explorer browser.As per the clients requirement, I need to save the screen-shot of a web page using the later ‘s URL.
I searched the web to find some help, but found nothing that matches my criteria, then i decided it do it my own way, write your own class file for converting a URL into an acceptable windows filename.
here is the code that will change a URL into a filename.
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions;
namespace Coderbuddy { public class FileNameFromURL { string URL = ""; public FileNameFromURL(string URL2CONVERT) { URL = URL2CONVERT; } public string CONVERT() { List<string> X = new List<string>(); string rt = ""; Regex r = new Regex(@"[a-z]+", RegexOptions.IgnoreCase); foreach (Match m in r.Matches(this.URL)) { X.Add(m.Value); } for (int i = 0; i < X.Count; i++) { rt = rt + X[i]; rt = rt + "_"; } return rt; } } }
To use the code, copy this code into your project, and declare the class, like
//replace http://yourURlhere.com with your own url in the bellow statement
FileNameFromURL ff = new FileNameFromURL("http://yourURlhere.com");
string File_Name = ff.CONVERT();
//use the File_Name to save your documents, etc..,