Why Directory.GetFiles() doesn't accept the input of the variable? - c#

using System;
using System.IO;
namespace GetFilesFromDirectory
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Write your Name of Disc");
string myDisc = Console.ReadLine();
string myDisc1 = "#\"";
Console.WriteLine("Write your Directory");
string myDir1 = Console.ReadLine();
string myDir = ":\\";
string myDir2 = "\\\"";
string myPath = myDisc1 + myDisc + myDir + myDir1 + myDir2;
Console.WriteLine(myPath);
string[] filePaths = Directory.GetFiles(myPath);
foreach (var files in filePaths)
{
Console.WriteLine(files);
}
Console.ReadLine();
}
}
}

Try this
static void Main(string[] args)
{
Console.WriteLine("Write your Name of Disc");
//You need to add :\ to make it a fullPath
string myDisc = Console.ReadLine()+":\\";
Console.WriteLine("Write your Directory");
string myDir1 = Console.ReadLine();
string myPath = Path.Combine(myDisc , myDir1);
Console.WriteLine(myPath);
string[] filePaths = Directory.GetFiles(myPath);
foreach (var files in filePaths)
{
Console.WriteLine(files);
}
Console.ReadLine();
}
What are you doing is creating a string wich is the literal reprentation of the string you want but you don't need to do this.For example if you write this:
string path=#"c:\dir\subdir"; its real value will be c:\dir\subdir
instead this "#\"c:\\dir\\subdir\""; will be
#"c:\dir\subdir"
Read these articles to better understand string literals and verbatim strings https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx https://msdn.microsoft.com/en-us/library/362314fe.aspx
https://msdn.microsoft.com/en-us/library/h21280bw.aspx

From what I can tell your myPath will look like #"discName:\dirName\", you don't need to append the #" or ".
These symbols are used when you are creating a new string variable to note that is a String literal, but you are including these characters in the actual string you are generating.
In other words, remove myDisc1 and myDir2
Better than that, as noted by DrKoch
string myPath = Path.Combine(myDisc + #":\", myDir1);

Related

Rename file 20181207_ProdAndPressuresExport.csv to ProdAndPressuresExport.csv

I have the following C# code but having issues renaming the file to what I want (ProdAndPressuresExport.csv). It is renaming the file as ProdAndPressuresExportProdAndPressuresExport.csv and also moving the rename file up 1 folder. I would like for it to stay in its original file path C:\TEMP\CSVFile\ProdAndPressuresExport. Please help.
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
const string DIRECTORY_PATH = #"C:\TEMP\CSVFile\ProdAndPressuresExport";
const string FILE_NAME_TEMPLATE = "*_ProdAndPressuresExport.CSV";
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH, FILE_NAME_TEMPLATE);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
string newName = DIRECTORY_PATH + filePath.Split('_')[1];
File.Move(filePath, newName);
}
}
}
}
}
}
Always use Path.Combine to construct paths, rather than string concatenation.
string newName = DIRECTORY_PATH + filePath.Split('_')[1];
Should be
string newName = Path.Combine(DIRECTORY_PATH, filePath.Split('_')[1]);
Otherwise you miss the directory separator character, and your file will end up in the parent folder above your intended folder with an unintentionally concatenated name.

Unable to fill list with content of a file

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> file1 = new List<string>();
Console.WriteLine("Enter the path to the folder");
string path1 = Console.ReadLine();
string text = System.IO.File.ReadAllText(path1);
}
}
}
I am trying to put the content of the file (text) into the list. I tried to look on this website for help but couldn't find anything.
If you want to have a list of each line use File.ReadAllLines.
List<string> file1 = new List<string>();
Console.WriteLine("Enter the path to the folder");
string path1 = Console.ReadLine();
file1.AddRange(System.IO.File.ReadAllLines(path1));
foreach(var line in file1)
{
Console.WriteLine(line);
}
This should work fine!
static void Main(string[] args)
{
List<string> file1 = new List<string>();
Console.Write("Enter the path to the folder:");
string path1 = Console.ReadLine();
file1.AddRange(System.IO.File.ReadAllLines(path1));
foreach(var line in file1)
{
Console.WriteLine(line);
}
Console.ReadKey();
}
Or this if you like lambda.
static void Main(string[] args)
{
List<string> file1 = new List<string>();
Console.Write("Enter the path to the folder:");
string path1 = Console.ReadLine();
file1.AddRange(System.IO.File.ReadAllLines(path1));
file1.ForEach(line => Console.WriteLine(line));
Console.ReadKey();
}

Editing files with with lists in C#?

I'm trying to teach myself how to edit files in C# and have encountered a problem. I am trying to allow the user to open a file that contains a sentence that says:
"How are you today, <name>?"
I have a class that will read the file and add the sentence to a List. Here is the code that I wrote for that:
class FileReader
{
public string reader(string sentence)
{
string f = sentence;
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
lines.Add(line);
}
return lines.ToString();
}
}
}
Once this is returned as a string, I have another class that will read the list, and then will ask the user for a name. It will then replace <name> with the name the user input. Here is the code I've tried writing to handle this:
class Asker
{
public string asker(string sentence)
{
List<string> lines = new List<string>();
Console.Write("Enter Name: ");
string name = Console.ReadLine();
string text = File.ReadAllText(sentence);
text = text.Replace("<name>", name);
lines.Add(text);
File.WriteAllText(sentence, text);
return lines.ToString();
}
}
By the end of this class, the Asker class should return a list containing the new sentence where name now replaces <name> in the original sentence. In main, I get an error code every time I try to run it. Here is main:
static void Main(string[] args)
{
Console.Write("Enter the name of the story file: ");
string filename = Console.ReadLine();
FileReader read = new FileReader();
string uneditedSentence = read.reader(filename);
Asker ask = new Asker();
string newSentence = ask.asker(uneditedSentence);
Console.WriteLine(newSentence);
}
When I run this program I get a message that it stopped working and just crashes.
Few Edits are required in your code:
1) When you are returning lines.toString()>> it would return System.Collections.Generic.List`1[System.String] and not the text in the file. So you should lines and not lines.String().
so the return type of your function would be List.
Or if you want to return the string then code would be:
class FileReader
{
public string reader(string sentence)
{
string f = sentence;
string lines = "";
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
lines +=line+ Environment.NewLine;
}
return lines;
}
}
}
2) In your asker class: asker function argument is the content of file and not the filename:
string text = File.ReadAllText(sentence)
so the above code will not work.
A better way: you dont need file reader class:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the name of the story file: ");
string filename = Console.ReadLine();
Asker ask = new Asker();
string newSentence = ask.asker(filename);
Console.WriteLine(newSentence);
string name = Console.ReadLine();
}
}
class Asker
{
public string asker(string sentence)
{
Console.Write("Enter Name: ");
string name = Console.ReadLine();
string text = File.ReadAllText(sentence);
text = text.Replace("<name>", name);
File.WriteAllText(sentence, text);
return text;
}
}
Your reader method accepts filename as the only argument and returns the contents of the file.
It means that in this line of code uneditedSentence is the contents of file filename:
string uneditedSentence = read.reader(filename);
Then, you pass this uneditedSentence to your asker:
string newSentence = ask.asker(uneditedSentence);
At the same time, your asker method has the following lines:
string text = File.ReadAllText(sentence);
File.WriteAllText(sentence, text);
which expects filepath while you provide contents of it.
It provides a error, because you provide an incorrect file path. The reason of this is very simple - naming. You name your variables inproperly and get confused.
Refer to MSDN documentation on ReadAllText and WriteAllText.
Also, it will not show proper results, because you apply ToString() to the List<string> expecting that it will be converted to the single string. However, it will simply result in something like System.Collections.Generic.List'1[System.String].
Here is how you should have done this:
class FileReader // Actually, it is a useless class, get rid of it
{
public string Read(string filename)
{
return File.ReadAllText(filename);
}
}

Update string at a specific line so it doesn't update duplicates in string?

I know how to go to a specific line but I don't know how to update that specific line in the string. I have tried the Replace functionality but it overwrites the duplicates as well. Any ideas?
static string GetLine(string text, int lineNo)
{
string[] lines = text.Replace("\r", "").Split('\n');
return lines.Length >= lineNo ? lines[lineNo - 1] : null;
}
static void Main(string[] args)
{
string file = "D:\\random.text";
string contents = "";
string text="random";
contents = File.ReadAllText(file);
finale=GetLine(contents,lines);
// Console.ReadLine();
if(finale.Contains(text))
{
finale.Replace(text,"Random");
System.Console.WriteLine(finale);
Console.ReadLine();
}
}
Strings are immutable type which means you cant alter an existing string. string.Replace returns the replaced string and you need to assign it back.
if(finale.Contains(text))
{
finale = finale.Replace(text,"Random"); //<- note here
System.Console.WriteLine(finale);
Console.ReadLine();
}
From there you need to rebuild the string from the string array as noted by Philippe. A complete example (but untested):
static string[] GetLines(string text)
{
return text.Replace("\r", "").Split('\n');
}
static string GetLine(string[] lines, int lineNo)
{
return lines.Length >= lineNo ? lines[lineNo - 1] : null;
}
static void Main(string[] args)
{
string file = "D:\\random.text";
string contents = "";
string text="random";
contents = File.ReadAllText(file);
var lines = GetLines(contents);
finale = GetLine(lines, lineNo);
//Console.ReadLine();
if (finale == null)
return;
if(finale.Contains(text))
{
finale = finale.Replace(text, "Random");
System.Console.WriteLine(finale);
Console.ReadLine();
}
lines[lineNo] = finale;
contents = string.Join('\n', lines);
}
And best of all, you don't need all that split function at all. .NET has that functionality and it does lazily (on demand) which is a bonus.
See for File.ReadLines if you're using .NET 4.0 and above.
The quickest solution would be to keep the array returned by Split and then use String.Join to rebuild what you started with.
Just rebuild the string with string builder as you read the file.
static void Main(string[] args)
{
string file = "D:\\random.txt";
string find = "random";
string replace = "Random";
StringBuilder resultList = new StringBuilder();
using (var stream = File.OpenText(file))
{
while (stream.Peek() >= 0)
{
string line = stream.ReadLine();
if(line == find)
{
line = replace;
}
resultList.AppendLine(line);
}
}
string result = resultList.ToString();
Console.WriteLine(result);
Console.Read();
}

Adding a newline into a string in C#

I have a string.
string strToProcess = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
I need to add a newline after every occurence of "#" symbol in the string.
My Output should be like this
fkdfdsfdflkdkfk#
dfsdfjk72388389#
kdkfkdfkkl#
jkdjkfjd#
jjjk#
Use Environment.NewLine whenever you want in any string. An example:
string text = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
text = text.Replace("#", "#" + System.Environment.NewLine);
You can add a new line character after the # symbol like so:
string newString = oldString.Replace("#", "#\n");
You can also use the NewLine property in the Environment Class (I think it is Environment).
The previous answers come close, but to meet the actual requirement that the # symbol stay close, you'd want that to be str.Replace("#", "#" + System.Environment.NewLine). That will keep the # symbol and add the appropriate newline character(s) for the current platform.
Then just modify the previous answers to:
Console.Write(strToProcess.Replace("#", "#" + Environment.NewLine));
If you don't want the newlines in the text file, then don't preserve it.
A simple string replace will do the job. Take a look at the example program below:
using System;
namespace NewLineThingy
{
class Program
{
static void Main(string[] args)
{
string str = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
str = str.Replace("#", "#" + Environment.NewLine);
Console.WriteLine(str);
Console.ReadKey();
}
}
}
as others have said new line char will give you a new line in a text file in windows.
try the following:
using System;
using System.IO;
static class Program
{
static void Main()
{
WriteToFile
(
#"C:\test.txt",
"fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#",
"#"
);
/*
output in test.txt in windows =
fkdfdsfdflkdkfk#
dfsdfjk72388389#
kdkfkdfkkl#
jkdjkfjd#
jjjk#
*/
}
public static void WriteToFile(string filename, string text, string newLineDelim)
{
bool equal = Environment.NewLine == "\r\n";
//Environment.NewLine == \r\n = True
Console.WriteLine("Environment.NewLine == \\r\\n = {0}", equal);
//replace newLineDelim with newLineDelim + a new line
//trim to get rid of any new lines chars at the end of the file
string filetext = text.Replace(newLineDelim, newLineDelim + Environment.NewLine).Trim();
using (StreamWriter sw = new StreamWriter(File.OpenWrite(filename)))
{
sw.Write(filetext);
}
}
}
string strToProcess = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
var result = strToProcess.Replace("#", "# \r\n");
Console.WriteLine(result);
Output
string str = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
str = str.Replace("#", Environment.NewLine);
richTextBox1.Text = str;
Based on your replies to everyone else, something like this is what you're looking for.
string file = #"C:\file.txt";
string strToProcess = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
string[] lines = strToProcess.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter writer = new StreamWriter(file))
{
foreach (string line in lines)
{
writer.WriteLine(line + "#");
}
}
Change your string as mentioned below.
string strToProcess = "fkdfdsfdflkdkfk"+ System.Environment.NewLine +" dfsdfjk72388389"+ System.Environment.NewLine +"kdkfkdfkkl"+ System.Environment.NewLine +"jkdjkfjd"+ System.Environment.NewLine +"jjjk"+ System.Environment.NewLine;
You could also use string[] something = text.Split('#'). Make sure you use single quotes to surround the "#" to store it as a char type.
This will store the characters up to and including each "#" as individual words in the array. You can then output each (element + System.Environment.NewLine) using a for loop or write it to a text file using System.IO.File.WriteAllLines([file path + name and extension], [array name]). If the specified file doesn't exist in that location it will be automatically created.
protected void Button1_Click(object sender, EventArgs e)
{
string str = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
str = str.Replace("#", "#" + "<br/>");
Response.Write(str);
}
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string strToProcess = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
strToProcess.Replace("#", Environment.NewLine);
Console.WriteLine(strToProcess);
}
}

Categories

Resources