How can I use the URL as Path using C# [Resolved]

Posted by Kasani007 under C# on 1/25/2016 | Points: 10 | Views : 1644 | Status : [Member] | Replies : 3
I have an URL that is taken in web.config i;e.,
<add key="FromLocation" value="http://198.12.16.1/"/>

and in the c# code

NameValueCollection loc = (NameValueCollection)ConfigurationManager.GetSection("EmailConfiguration");

string urlPath = loc["FromLocation"];

string fileLocation=urlPath + @"\SampleText\sample.txt;

my requirement is like above
but it is not recognising as filelocation path , if i use
if (File.Exists(fileLocation))
{
}

please help me..




Responses

Posted by: Rajnilari2015 on: 1/25/2016 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
Try this

using System;
using System.Net;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string fileLocation = @"<YOUR URL>";
var serverResponse = GetServerResponse(fileLocation);
Console.WriteLine("URL Validity : {0} \n Server Response : {1}", serverResponse.Item1, serverResponse.Item2);
Console.ReadKey();
}

private static Tuple<bool,string> GetServerResponse(string fileLocation)
{
bool isValidURL = true;
string data = string.Empty;
using (WebClient client = new WebClient())
{
try
{
data = client.DownloadString(fileLocation);
}catch(WebException weX){
isValidURL = !isValidURL;
data = weX.Message;
}
}
return Tuple.Create<bool, string>(isValidURL, data);
}
}
}


Case 1: When Success
URL Validity : True
Server Response : This is a sample test


Case 2: When Failure(Wrong URL)

URL Validity : False
Server Response : The remote name could not be resolved: xyz.cloudapp.net'


Hope that helps.

--
Thanks & Regards,
RNA Team

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sheonarayan on: 1/25/2016 [Administrator] HonoraryPlatinum | Points: 25

Up
1
Down
You need to use Server.MapPath() - this function converts the virtual path to physical path.

In the web.config FromLocation value should not be "http://...." but it should be from the root of the application. Like

<add key="FromLocation" value="/" >
root of the application

string urlPath = Server.MapPath(urlPath);
string fileLocation=urlPath + @"\SampleText\sample.txt;

Now this should recognise the file location.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Professionaluser on: 1/25/2016 [Member] [MVP] Bronze | Points: 25

Up
0
Down
this link might help you

http://abundantcode.com/how-to-combine-url-in-c/

you try to check for file existence after combining URL

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response