Wednesday, February 9, 2011

Read Simple Text from .txt

Recently I was asked to create a portion on a web application. The basic requirement was to make the app able to read simple text from a text file (.txt) in a configurable location. The path would be located in the web.config and might be both a Web (URL) or physical (windows-style) address. In addition the file may or not exist... so here is the code I wrote:


        private string GetTextFromFile() 
{
string returnValue = string.Empty;

try
{
string path = Convert.ToString(ConfigurationManager.AppSettings["keyTextFile"]);
StringBuilder sb = new StringBuilder();

// make the difference between Url and Windows-style Path
if (path.Contains("http") || path.Contains(Path.AltDirectorySeparatorChar))
{
path = path.TrimEnd('/');
path = sb.Append(path).Append("//").Append("theFile.txt").ToString();

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(path);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
returnValue = reader.ReadToEnd();
}
else
{
path = Path.Combine(path, "theFile.txt");

if (File.Exists(path))
{
using (StreamReader sr = new StreamReader(path))
{
returnValue = sr.ReadToEnd();
}
}
}
}
catch
{
returnValue = string.Empty;
}

return returnValue;
}

No comments:

Post a Comment