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();
}
Related
within my Csv File i have a column which holds a string and a datetime type. i would like to separate these data in two columns, one column which holds the string and one which holds the date but converts the datetime type as a string too.
After doing some research i noticed that i could use the string.split function which will add a comma after the three character which are TIP and then push the date in a new column. however i do not know to code this process
class Program
{
static void Main(string[] args)
{
string currentDirectory = Directory.GetCurrentDirectory();
DirectoryInfo directory = new DirectoryInfo(currentDirectory);
var fileName = Path.Combine(directory.FullName, "Climate 02_08_2016.csv");
var fileContents = ReadFile(fileName);
string[] fileLines = fileContents.Split(new char[] { 'r', 'n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in fileLines)
{
Console.WriteLine(line);
}
}
public static string ReadFile(string fileName)
{
var column5 = new List<string>();
using (var reader = new StreamReader(fileName))
{
while (reader.EndOfStream)
{
var splits = reader.ReadLine().Split(';');
column5.Add(splits[4]);
}
return reader.ReadToEnd();
}
}
}
String.Split splits a string into array of strings based on a delimiter specified. MSDN Reference.
You could use String.Replace method to replace space with a comma.
var result = yourStringVar.Replace(' ', ',')
Here is the full code (slightly simplified).
class Program
{
static void Main(string[] args)
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Climate 02_08_2016.csv");
var fileContents = ReadFile(filePath);
foreach (var line in fileContents)
{
Console.WriteLine(line);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
public static IList<string> ReadFile(string fileName)
{
var results = new List<string>();
var lines = File.ReadAllLines(fileName);
for (var i = 0; i < lines.Length; i++)
{
// Skip the line with column names
if (i == 0)
{
continue;
}
// Replace space with a comma
var replace = lines[i].Replace(' ', ',');
results.Add(replace);
}
return results;
}
}
I get following output:
TUI,01/01/20
Press any key to exit...
Please let me know if this is enough for you to implement your own solution.
I've created a file extractor, now it does work, however it also moves all the files from the startDir to the destDir along with, the zip file. How can I get this program to only move the zip file, instead of all the files?
Source:
using System;
using System.IO.Compression;
namespace ArchiveCreator
{
class Program
{
//When program is run successfully this will be the output
public string Success(string input)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(input);
return input;
}
//When program encounters an error this will be the output
public string Warn(string input)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(input);
return input;
}
//When program has information to show, this will be the output
public string Say(string input)
{
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine(input);
return input;
}
//Main method
static void Main(string[] args)
{
//These variables are used to create a
//random string that will be used as the
//zip files name
var chars = "abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var stringChars = new char[8];
var random = new Random();
//Info is used as provide the type of
//information that will be displayed
//by the program
Program info = new Program();
//Create the zip file name
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
string finalString = new String(stringChars);
info.Say("Starting file extraction..");
string startDir = #"c:/users/thomas_j_perkins/test_folder";
string destDir = #"c:/users/thomas_j_perkins/archive/";
string zipName = $"c:/users/thomas_j_perkins/archive/{finalString}.zip";
try
{
ZipFile.CreateFromDirectory(startDir, zipName);
ZipFile.ExtractToDirectory(zipName, destDir);
}
catch (Exception e)
{
info.Warn($"Error: {e}");
}
info.Success($"Extracted files successfully to: {destDir}");
info.Say("Press enter to exit..");
Console.ReadLine();
}
}
}
Image of directory after program is run:
Your code is creating a zip file in the destination directory when you call
ZipFile.CreateFromDirectory(startDir, zipName);
The zipname path is in the destDir. Did you mean to put it in the startDir?
string startDir = #"c:/users/thomas_j_perkins/test_folder";
string destDir = #"c:/users/thomas_j_perkins/archive/";
string zipName = $"c:/users/thomas_j_perkins/archive/{finalString}.zip";
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);
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();
}
I want to access the path for my directory, but I can not. I put a breakpoint in my code:
string directoryPath = args[0];
And when i clicked on the args[0];, it showed me this image:
- args {string[3]} string[]
[0] "C:\\Users\\soft\\Documents\\Visual" string
[1] "Studio" string
[2] "2010\\Projects\\erereerer\\erereerer\\bin\\Debug\\MAXee\\" string
directoryPath null string
filesList null string[]
filesListTmp null string[]
opList null erereerer.IFileOperation[]
I have been trying to access my directory but I have been failing. I tried so many times but when I run my code its saying directory does not exist while the directory is in fact there..
This is my code:
class Program
{
static void Main(string[] args)
{
string directoryPath = args[0];
string[] filesList, filesListTmp;
IFileOperation[] opList = { new FileProcNameAfter10(),
new FileProcEnc(),
new FileProcByExt("jpeg"),
new FileProcByExt("jpg"),
new FileProcByExt("doc"),
new FileProcByExt("pdf"),
new FileProcByExt("djvu")
};
if (Directory.Exists(directoryPath))
{
filesList = Directory.GetFiles(directoryPath);
while (true)
{
Thread.Sleep(500);
filesListTmp = Directory.GetFiles(directoryPath);
foreach (var elem in Enumerable.Except<string>(filesListTmp, filesList))
{
Console.WriteLine(elem);
foreach (var op in opList)
{
if (op.Accept(elem)) op.Process(elem);
}
}
filesList = filesListTmp;
if (Console.KeyAvailable == true && Console.ReadKey(true).Key == ConsoleKey.Escape) break;
}
}
else
{
Console.WriteLine("There is no such directory.");
Console.ReadKey();
}
}
}
[0] "C:\Users\soft\Documents\Visual" string
[1] "Studio" string
[2] "2010\Projects\erereerer\erereerer\bin\Debug\MAXee\" string
It tells me that you are passing the arguments without quotes.
Call you program this way:
MyApp.exe "C:\Users\soft\Documents\Visual Studio 2010\Projects\erereerer\erereerer\bin\Debug\MAXee\"
Or just do what Blachshma said:
directoryPath = String.Join(" ", args);
Either pass the directory in quotes:
MyProgram.exe "C:\Users\soft\Documents\Visual Studio 2010\Projects\erereerer\erereerer\bin\Debug\MAXee\"
or Join the args in code:
directoryPath = String.Join(" ", args);