Hi I'm writing a c# code where in there is a string sent as a parameter input to the method. And then the inputString has to be searched in the file and the result has to be returned. Currently I know how do I do this in the regular way(using the file IO).
[HttpPost]
public string UsernameValidation(string username)
{
string text = username;
string userExists = usernameNotAvailable;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("~/UserData/usernameslist.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(text))
{
userExists = usernameAvailable;
}
}
return userExists;
}
But here is the twist, my project is in MVC. I'm able to get the path of file using string userDataFile = Server.MapPath("~/UserData/usernameslist.txt");.
But I'm unable to know how can I get the functionality of searching a string in a file.
Please let me know how can I do this.
Thanks
If the the file usernameslist.txt really exists inside a subfolder named UserData from your root folder then you just need to pass the output of Server.MapPath to your StreamReader constructor
string fileName = Server.MapPath("~/UserData/usernameslist.txt");
using(StreamReader file = new System.IO.StreamReader(fileName))
{
....
}
And don't forget to use the using statement around a Stream object
Related
I have a Save ActionResult in my Controller that is set up to use StreamWriter. The code works perfectly, for saving to a file that exists.
Save Action
[HttpPost]
[ValidateInput(false)]
public ActionResult Save(string fileName, string startTemplateUrl, string html)
{
string directoryname = Path.GetDirectoryName(fileName);
string filename = Path.GetFileName(fileName);
var lines = html;
var helper = (Server.MapPath(directoryname));
using (StreamWriter outputFile = new StreamWriter(Path.Combine(helper, filename)))
{
outputFile.WriteLine(lines);
return View();
}
}
I am now working on a file creation and from what i have read you can do this with StreamWriter although when I try to implement it, it says it cannot be found. Which tells me it is looking for a file instead of creating it.
So I tried to implement this using FileInfo. It appears that it has everything it needs but just doesn't save it. Below is my latest code. It does not like the
fs.Write(lines);
I had a try catch block. on this and it had the same results. That it cannot find it.
[HttpPost]
[ValidateInput(false)]
public ActionResult Create (string fileName, string startTemplateUrl, string html)
{
string directoryname = Path.GetDirectoryName(fileName);
string filename = Path.GetFileName(fileName);
var lines = html;
var helper = (Server.MapPath(directoryname));
var file = "Test\\" + filename;
var pathString = System.IO.Path.Combine(helper, "Test\\", filename);
FileInfo fi = new FileInfo(pathString);
if (fi.Exists)
{
fi.Delete();
}
using (FileStream fs = fi.Create())
{
fs.Write(lines);
return View();
}
}
Thanks for your help!
Update:
This is the message I get. Below the message I have the actual string to the directory copied from folder explorer..
Exception thrown: 'System.IO.DirectoryNotFoundException' in mscorlib.dll
An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code
Could not find a part of the path 'C:\Users\Scott\source\repos\HMIBuilder\HMIBuilder\Files\HMIBuider\Test\Test2.html'.
C:\Users\Scott\source\repos\HMIBuilder\HMIBuilder\Files\HMIBuilder\Test
Update:
I need to look at my code better! This is fixed.. The code at the very top works perfectly for both save and create. The problem was in the javascript code variables that i was feeding it. A Typo... If you look at the above comparison, which I did not catch myself, too many long nights I suppose, HMIBuilder is spelled HMIBuider... in the error.
using (StreamWriter outputFile = new StreamWriter(Path.Combine(path, "filename.txt")))
would create a new file, if needed.
Your problem may be the Test directory and CreateDirectory is here to help.
DirectoryInfo di = Directory.CreateDirectory(path);
If we put the writing to the file and creating directories together it could look like the following snippet.
var path = "./MyFiles/SpecialFiles";
var filename = "thisIsAVerySpecialFile.txt";
Directory.CreateDirectory(path);
//Create a new file or overwrite existing (i.e. *not* append)
using (var f = new StreamWriter(Path.Combine(path, filename)))
{
f.WriteLine("Hello world!");
}
Without Directory.CreateDirectory the code results in System.IO.DirectoryNotFoundException with 'Could not find a part of the path '(...)'.
I am working on a project that is reading the data from a Azure Blob and saving that data into an Object. I am currently running into a problem. The way my code is set up now - it will read all the .txt data within a container if there are no Virtual Folders present.
However, if there is a virtual folder structure present within a Azure Container
my code will error out, with a NullExceptionReference. My idea was to do a if check to see if there was Virtual Folders present within an Azure Container if so execute //some code. Is there a way to tell if there is a virtual folder is present?
ReturnBlobObject()
private List<Blob> ReturnBlobObject(O365 o365)
{
List<Blob> listResult = new List<Blob>();
string textToFindPattern = "(\\/)";
string fileName = null;
string content = null;
//Loop through all Blobs and split the container form the file name.
foreach (var blobItem in o365.Container.ListBlobs(useFlatBlobListing: true))
{
string containerAndFileName = blobItem.Parent.Uri.MakeRelativeUri(blobItem.Uri).ToString();
string[] subString = Regex.Split(containerAndFileName, textToFindPattern);
//subString[2] is the name of the file.
fileName = subString[2];
content = ReadFromBlobStream(o365.Container.GetBlobReference(subString[2]));
Blob blobObject = new Blob(fileName, content);
listResult.Add(blobObject);
}
return listResult;
}
ReadFromBlobStream
private string ReadFromBlobStream(CloudBlob blob)
{
Stream stream = blob.OpenRead();
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
I was able to solve this by refactoring my code. Instead of using Regex - which was returning some very odd behavior I decided to take a step back and think the problem. Below is the solution I came up with.
ReturnBlobObject()
private List<Blob> ReturnBlobObject(O365 o365)
{
List<Blob> listResult = new List<Blob>();
//Loop through all Blobs and split the container form the file name.
foreach (var blobItem in o365.Container.ListBlobs(useFlatBlobListing: true))
{
string fileName = blobItem.Uri.LocalPath.Replace(string.Format("/{0}/", o365.Container.Name), "");
string content = ReadFromBlobStream(o365.Container.GetBlobReference(fileName));
Blob blobObject = new Blob(fileName, content);
listResult.Add(blobObject);
}
return listResult;
}
I have the following text file called urlmap.txt in App_Data
ShowProduct.aspx?ID=1143, laptops/1143/laptops-for-beginner-experienced-engineers
ShowProduct.aspx?ID=1142, desktops/1142/dynamic-difference-desktops
ShowProduct.aspx?ID=1141, keyboards/1141/bluetooth-ready-keyboards
ShowProduct.aspx?ID=1140, mouse/1140/microsoft-2key-mouse-with-pad
ShowProduct.aspx?ID=1139, mouse/1139/logitech-3key-mouse-auto-shutoff
and about 2000 such entries....
I want to pass in a string like "ShowProduct.aspx?ID=1140" and search and retrieve the text in front of it i.e. "mouse/1140/microsoft-2key-mouse-with-pad"
If this string is not found, it retrieves nothing.
Each string in urlmap.txt is unique, so there is no chance of duplication
How can I do this?
This is what I have so far but I am unable to determine how to retreive the text in front of it
string line;
StringBuilder sb = new StringBuilder();
using (System.IO.StreamReader file = new System.IO.StreamReader("App_Data\urlmap.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(mySearchString))
{
}
}
}
Since the text file contains about 2000+lines, I also need an optimized way of retrieving the record.
Just use Split:
if (line.Contains(mySearchString))
{
var text = line.Split(",")[1];
/*do something else with text*/
}
I have a method to get the folder path of a particular file:
string filePath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments), "file.txt");
And later, I use this to read the text in the file:
StreamReader rdr = new StreamReader(filePath); // "C:\Users\<user>\Documents\file.txt"
string myString = rdr.ReadToEnd();
Trouble is, if the file doesn't exist, it throws a FileNotFoundException (obviously). I want to hopefully use an if/else to catch the error, in which the user can browse to find the file directly, but I'm not sure what to use to verify if filePath is valid or not.
For example, I can't use:
if (filePath == null)
because the top method to retrieve the string will always return a value, whether or not it is valid. How can I solve this?
While File.Exists() is appropriate as a start, please note that ignoring the exception can still lead to an error condition if the file becomes inaccessible (dropped network drive, file opened by another program, deleted, etc.) in the time between the call to File.Exists() and new StreamReader().
You can use File.Exists:-
if(File.Exists(filePath))
{
//Do something
}
else
{
}
string filePath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments), "file.txt");
if(!File.Exists(filePath))
{
/* browse your file */
}
else
{
StreamReader rdr = new StreamReader(filePath); // "C:\Users\<user>\Documents\file.txt"
string myString = rdr.ReadToEnd();
}
I am uploading a file into a controller using the following -
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
//I want to put file contents into a string or List<string>
}
}
I would like to either put the contents of the file into a string then loop through the string which will be a delimited list,
or
loop through the incoming stream itself, creating a list of strings out of it.
I can't figure out how to do either. I assume I would use file.InputStream in some manner?
Any help would be appreciated. Thanks!
Try using StreamReader, something like this:
string s = (new StreamReader(file.InputStream)).ReadToEnd();
string[] ss = s.Split(","); // replace "," with your separator;