I'm trying to write a unix2dos program to alter the line feeds of text files.
The problem is instead of altering the contents of a text file, the file name was appended instead.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace unix2dos
{
class Program
{
static void Main(string[] args)
{
string[] filePaths = Directory.GetFiles(#"c:\textfiles\", "*.txt");
foreach (string file in filePaths)
{
string[] lines = File.ReadAllLines(file);
foreach (string line in lines)
{
string replace = line.Replace("\n", "\r\n");
File.WriteAllText(file, replace);
}
}
}
}
}
Because you are writing the string and overwriting it.
Try this:
string[] filePaths = Directory.GetFiles(#"c:\textfiles\", "*.txt");
foreach (string file in filePaths)
{
string[] lines = File.ReadAllLines(file);
List<string> list_of_string = new List<string>();
foreach (string line in lines)
{
list_of_string.Add( line.Replace("\n", "\r\n"));
}
File.WriteAllLines(file, list_of_string);
}
Related
I have write a c# code to retrieve all the file names follow by printing one of the information inside. Example File contains (file1.mht, file2.mht, file3.mht). Maybe the contain inside is (aaaaaa, bbbbbb, cccccc) follow the sequence of the file.
Example out output:
file1.mht aaaaaa
file2.mht bbbbbb
file3.mht cccccc
But I encounter the problem it cannot loop the file name follow by showing the content inside. Anyone can helps? Current result is it show all the directory first and only done the work for the first one in directory.
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections.Specialized;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo mht_file = new DirectoryInfo(#"C:\Users\liewm\Desktop\SampleTest\");
FileInfo[] Files = mht_file.GetFiles("*.mht");
string str = "";
string mht_text = "";
string directory = "";
string listInfo = "";
foreach (FileInfo file in Files)
{
str = file.Name;
directory = mht_file + str;
Console.WriteLine(directory);
}
foreach (char filePath in directory)
{
//Here is my work to retrieve the data in the file
Console.WriteLine("Names:" + str + " " + "Component:" + component);
Console.ReadKey();
}
}
}
}
From your question I understand that you want to print the file name followed by the content of the same, if so you can try:
DirectoryInfo mht_file = new DirectoryInfo(#"C:\Users\liewm\Desktop\SampleTest\");
FileInfo[] Files = mht_file.GetFiles("*.mht");
foreach (FileInfo file in Files)
{
// read the content of the file
var content = File.ReadAllText(file.FullName);
// from your question "Example out output: file1.mht aaaaaa"
Console.WriteLine($"{file.Name} {content}");
}
only done the work for the last one in directory.
Yes, that's cause your directory variable is a string string directory = "" which will get overridden by the last value of loop iteration. You rather want to store in a string[] rather if you want to process all of them.
foreach (FileInfo file in Files)
{
str = file.Name;
directory = mht_file + str;
Console.WriteLine(directory);
}
Please try this.
foreach (FileInfo file in Files)
{
str = file.Name;
directory += mht_file + str;
Console.WriteLine(directory);
}
I need to compare files found in a directory with another directory and print the files new files found in a directory into the console. I have it setup so it takes the files and assigns it to a variable. The other directory is assigned to another variable. How can I print the new data in one of the variables to command prompt?
The language I am using is c#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Write the path of the old file folder: ");
string path = Console.ReadLine();
listFilesFromDirectory(path);
Console.Write("Write the path of the new file folder: ");
string pathTwo = Console.ReadLine();
listFilesFromDirectoryMore(pathTwo);
Console.WriteLine("Press Enter to continue:");
Console.Read();
}
static void listFilesFromDirectory(string workingDirectory)
{
// get a list of files in a directory,
// based upon a path that is passed into the function
string[] filePaths = Directory.GetFiles(workingDirectory);
foreach (string filePath in filePaths)
{
// use the foreach loop to go through the entire
// array one element at a time write out
// the full path and file name of each of the
// elements in the array
Console.WriteLine(filePath);
string oldfile = (filePath);
}
}
static void listFilesFromDirectoryMore(string workingDirectoryTwo)
{
// get a list of files in a directory,
// based upon a path that is passed into the function
string[] filePathsTwo = Directory.GetFiles(workingDirectoryTwo);
foreach (string filePathTwo in filePathsTwo)
{
// use the foreach loop to go through the entire
// array one element at a time write out
// the full path and file name of each of the
// elements in the array
Console.WriteLine(filePathTwo);
string newfile = (filePathTwo);
}
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Write the path of the old file folder: ");
string pathA = Console.ReadLine();
Console.Write("Write the path of the new file folder: ");
string pathB = Console.ReadLine();
Console.WriteLine("Press Enter to continue:");
List<string> folderA = new List<string>();
foreach (string filePath in Directory.GetFiles(pathA))
{
folderA.Add(Path.GetFileName(filePath));
}
List<string> folderB = new List<string>();
foreach (string filePath in Directory.GetFiles(pathB))
{
folderB.Add(Path.GetFileName(filePath));
}
Console.Write("New files in folder" + pathA + " : ");
Print(folderA, folderB);
Console.WriteLine("------------------------------------");
Console.Write("New files in folder" + pathB + " : ");
Print(folderB, folderA);
Console.Read();
}
static void Print(List<string> lstA, List<string> lstB)
{
foreach (string fileName in lstA)
{
if (!lstB.Contains(fileName))
{
Console.Out.WriteLine(fileName);
}
}
}
}
}
I am currently trying to make an .exe in c# that I can drag and drop a .txt file onto to remove lines of text that contain the keywords "CM" and/or "Filling". It must be able to overwrite the existing data so there are no new files created. The filename is different every time except for the extension. The data is tab delimited if that has any bearing. I'm aware that there are similar questions to this but I haven't managed to adapt them to suit my needs. Also, I'm very new to this and I've been trying for about a week with no luck.
if (args.Length == 0)
return; // return if no file was dragged onto exe
string text = File.ReadAllText("*.txt");
text = text.Replace("cm", "");
string path = Path.GetDirectoryName(args[0])
+ Path.DirectorySeparatorChar
+ Path.GetFileNameWithoutExtension(args[0])
+ "_unwrapped" + Path.GetExtension(args[0]);
File.WriteAllText("*.txt", text);
\\attempt 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
string concrete = "CM";
string line;
using (StreamReader reader = new StreamReader(#"C:\\Users\drocc_000\Desktop\1611AN24T99-041805221704.txt"))
{
using (StreamWriter writer = new StreamWriter(#"C:\\Users\drocc_000\Desktop\1611AN24T99-041805221704NEW.txt"))
{
while ((line = reader.ReadLine()) != null)
{
// if (String.Compare(line, yourName) == 0)
// continue;
writer.WriteLine(line.Replace(concrete, ""));
}
}
}
\\attempt 2
Thanks for your time.
Regards,
Danny
You can create a console application with the code below and then drag and drop your text file into the .exe file without opening it.
class Program
{
static void Main(string[] args)
{
if (args.Length > 0 && File.Exists(args[0]))
{
string path = args[0];
EditFile(new List<string>() { "CM", "Filling" }, path);
}
Console.Read();
}
public static void EditFile(List<string> keyWords, string filename)
{
List<string> lines = new List<string>();
using (StreamReader sr = new StreamReader(filename))
{
while (sr.Peek() >= 0)
{
lines.Add(sr.ReadLine());
}
sr.Close();
}
int removedLinesCount = 0;
bool writeline;
using (StreamWriter sw = new StreamWriter(filename))
{
foreach (var line in lines)
{
writeline = true;
foreach (var str in keyWords)
{
if (line.Contains(str))
{
writeline = false;
removedLinesCount++;
break;
}
}
if (writeline)
sw.WriteLine(line);
}
Console.WriteLine(removedLinesCount + " lines removed from the file " + filename);
sw.Close();
}
}
}
Something like this?
using System;
using System.IO;
using System.Linq;
namespace ConsoleApp1
{
internal static class Program
{
private static void Main(string[] args)
{
try
{
// Get the filename from the applications arguments
string filename = args[0];
// Read in all lines in the file.
var linesInFile = File.ReadLines(filename);
// Filter out the lines we don't need.
var linesToKeep = linesInFile.Where(line => !line.Contains("CM") && !line.Contains("Filling")).ToArray();
// Overwrite the file.
File.WriteAllLines(filename, linesToKeep);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
I am trying to split a string in a .txt-file by commas (,) into a string[] and then replacing every item of the string[] to another formula, for example:
"Marko Kostic, Faculty of Technical Sciences, University of Novi Sad,
Trg D. Obradovica 6, 21125 Novi Sad, Serbia"
I want to split this string by commas in between the words and then I want to put every value in separate line like a list and then changing every value with another like "Marko Kostic" to be
<addr-line>Marko Kostic<\addr-line>
The problem is the writer wrote only the last value of string[] and erase the previous values.
Any suggestions?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Word;
using System.Diagnostics;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
namespace AffiliationParser
{
class Program
{
static void Main(string[] args)
{
Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
object missing = System.Reflection.Missing.Value;
object isVisible = false;
using (StreamReader batch = new StreamReader(#"D:\Developing\REF\AffiliationParser\AffiliationParser\AffiliationParser\bin\Debug\Run.bat"))
{
string bat;
while (!batch.EndOfStream)
{
bat = batch.ReadLine();
// do your processing with batch command
if (bat == "pause")
{
continue;
}
string fpath = bat.Substring(bat.IndexOf(" \""));
string path = fpath.Replace("\"", "").Replace(" ","");
string[] name = Directory.GetFiles(path, "*.txt");
string words = name.Min();
string word = words.Substring(words.LastIndexOf("\\")).Replace("\\", "");
Console.WriteLine("Processing........");
Console.WriteLine(word);
string Npath = path + #"\Arr" + word;
if (File.Exists(Npath))
{
System.Windows.Forms.MessageBox.Show("The file Arr" + word + " alredy exist in " + path);
continue;
}
else
{
File.Copy(words, Npath);
StreamReader temp = new StreamReader(Npath, Encoding.UTF8);
string tempstring = temp.ReadToEnd();
string[] temp3 = tempstring.Split(',');
temp.Close();
foreach (string item in temp3)
{
string Nitem = item.TrimStart().TrimEnd();
//Match MatchCont = Regex.Match(Nitem, #"Afganistan|Albania|Algeria|American\s+Samoa|Andorra|Angola|Anguilla|Antarctica|Antigua\s+and\s+Barbuda|Argentina|Armenia|Aruba|Australia|Austria|Azerbaijan|Bahamas|Bahrain|Bangladesh|Barbados|Belarus|Belgium|Belize|Benin|Bermuda|Bhutan|Bolivia|Bosnia\s+and\s+Herzegovina|Botswana|Bouvet\s+Island|Brazil|British\s+Indian\s+Ocean\s+Territory|Brunei\s+Darussalam|Bulgaria|Burkina\s+Faso|Burundi|Cambodia|Cameroon|Canada|Cape\s+Verde|Cayman\s+Islands|Central\s+African\s+Republic|Chad|Chile|China|Christmas\s+Island|Cocos\s+\(Keeling\)\s+Islands|Colombia|Comoros|Democratic\s+People's\s+Republic\s+of\s+Korea|Democratic\s+Republic\s+of\s+Congo|Cook\s+Islands|Costa\s+Rica|Cote\s+D'Ivoire|Croatia|Cuba|Cyprus|Czech\s+Republic|Republic\s+of\s+Korea|Denmark|Djibouti|Dominica|Dominican\s+Republic|East\s+Timor|Ecuador|Egypt|El\s+Salvador|Equatorial\s+Guinea|Eritrea|Estonia|Ethiopia|Falkland\s+Islands\s+\(Malvinas\)|Faroe\s+Islands|Fiji|Finland|France\s+Metropolitan|France|French\s+Guiana|French\s+Polynesia|French\s+Southern\s+Territories|Gabon|Gambia|Georgia|Germany|Ghana|Gibraltar|Greece|Greenland|Grenadaf|Guadeloupe|Guam|Guatemala|Guinea|Guinea\-Bissau|Guyana|Haiti|Heard\s+Island\s+and\s+McDonald\s+Island|Honduras|Hong\s+Kong|Hungary|Iceland|India|Indonesia|Iran|Iraq|Ireland|Northern\s+Ireland|Isle\s+Of\s+Man|Israel|Italy|Jamaica|Japan|Jordan|Kazakhstan|Kenya|Kiribati|Kuwait|Kyrgyzstan|Lao\s+People'S\s+Democratic\s+Republic|Latvia|Lebanon|Lesotho|Liberia|Libya|Liechtenstein|Lithuania|Luxembourg|Macau|Macedonia|Madagascar|Malawi|Malaysia|Maldives|Mali|Malta|Marshall\s+Islands|Martinique|Mauritania|Mauritius|Mayotte|Mexico|Micronesia|Moldova|Monaco|Mongolia|Montserrat|Morocco|Mozambique|Myanmar|Namibia|Nauru|Nepal|Netherlands\s+Antilles|New\s+Caledonia|New\s+Zealand|Nicaragua|Nigeria|Niger|Niue|Norfolk\s+Island|Northern\s+Mariana\s+Islands|Norway|Oman|Pakistan|Palau|Palestine|Panama|Papua\s+New\s+Guinea|Paraguay|Peru|Philippines|Pitcairn|Poland|Portugal|Puerto\s+Rico|Qatar|Reunion|Romania|Russia|Rwanda|Saint\s+Kitts\s+and\s+Nevis|Saint\s+Lucia|Saint\s+Vincent\s+and\s+The\s+Grenadines|Samoa|San\s+Marino|Sao\s+Tome\s+and\s+Principe|Saudi\s+Arabia|Scotland|Senegal|Serbia|Kosovo|Montenegro|Seychelles|Sierra\s+Leone|Singapore|Slovakia|Slovenia|Solomon\s+Islands|Somalia|South\s+Africa|South\s+Georgia\s+and\s+The\s+South\s+Sandwich\s+Islands|Spain|Sri\s+Lanka|St.\s+Helena|St.\s+Pierre\s+and\s+Miquelon|Sudan|Suriname|Svalbard\s+and\s+Jan\s+Mayen\s+Islands|Swaziland|Sweden|Switzerland|Syria|Taiwan|Tajikistan|Tanzania|Thailand|The\s+Netherlands|Togo|Tokelau|Tonga|Trinidad\s+and\s+Tobago|Tunisia|Turkey|Turkmenistan|Turks\s+and\s+Caicos\s+Islands|Tuvalu|Uganda|Ukraine|United\s+Arab\s+Emirates|UAE|UK|United\s+States\s+Minor\s+Outlying\s+Islands|Uruguay|USA|Uzbekistan|Vanuatu|Vatican\s+City\s+State\s+\(Holy\s+See\)|Venezuela|Vietnam|British\s+Virgin\s+Islands|USA\s+Virgin\s+Islands|Wallis\s+and\s+Futuna\s+Islands|Western\s+Sahara|West\s+Indies|Yemen|Zambia|Zimbabwe|Abkhazia|Afghanistan|Akrotiri\s+and\s+Dhekelia|Aland|Ascension\s+Island|The\s+Bahamas|Brunei|Central\s+Africa|Cocos|Congo|Cote\s+d'lvoire|Czech|Dominican|Falkland\s+Islands|Cambia,\s+The|Grenada|Guemsey|Isle\s+of\s+Man|Jersey|Korea|Laos|Macao|Nagorno\-Karabakh|Netherlands|Northern\s+Cyprus|Pitcaim\s+Islands|Sahrawi\s+Arab\s+Democratic|Saint\-Barthelemy|Saint\s+Helena|Saint\s+Martin|Saint\s+Pierre\s+and\s+Miquelon|Saint\s+Vincent\s+and\s+Grenadines|Samos|Somaliland|South\s+Ossetia|Svalbard|Transnistria|Tristan\s+da\s+Cunha|United\s+Kingdom|Vatican\s+City|Virgin\s+Islands|Wallis\s+and\s+Futuna|Espa�a|Witsch|United\s+States|Prague\s+Czech\s+Republic", RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
//if (MatchCont.Success==true)
//{
// MatchCont.Result(#"<country>" + Nitem + #"<\country>");
//}
}
}
}
}
}
}
}
Try to include code in you question, it's not a best practice to simply hand out answers. That being said, you'll want to look at the String.Split method, String.Trim and the File.AppendText method.
Simple ways to do this:
string[] stuff = data.Split(',');
StreamWriter sW = File.AppendText(pathToFile);
foreach(string parts in stuff)
{
sW.WriteLine(parts.Trim());
}
Very, very basic, and not giving you the answer without some work on your part. Good luck!
Here's some references: File.AppendText and String.Trim
string input="a,b,c,d";
string [] parts=input.Split(",",StringSplitOptions.RemoveEmptyEntries);
List<string> output=new List<string>();
foreach(string s in parts)
{
// do sth you like;
var newStr="<abc>"+s+"</abc>";
output.Add(newStr);
}
return output.ToArray();
When I use the line of code as below , I get an string array containing the entire path of the individual files .
private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf");
I would like to know if there is a way to only retrieve the file names in the strings rather than the entire paths.
You can use Path.GetFileName to get the filename from the full path
private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf")
.Select(Path.GetFileName)
.ToArray();
EDIT: the solution above uses LINQ, so it requires .NET 3.5 at least. Here's a solution that works on earlier versions:
private string[] pdfFiles = GetFileNames("C:\\Documents", "*.pdf");
private static string[] GetFileNames(string path, string filter)
{
string[] files = Directory.GetFiles(path, filter);
for(int i = 0; i < files.Length; i++)
files[i] = Path.GetFileName(files[i]);
return files;
}
You can use the method Path.GetFileName(yourFileName); (MSDN) to just get the name of the file.
You could use the DirectoryInfo and FileInfo classes.
//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf");
//FileInfo has a Name property that only contains the filename part.
var firstPdfFilename = pdfFiles[0].Name;
string[] fileEntries = Directory.GetFiles(directoryPath);
foreach (var file_name in fileEntries){
string fileName = file_name.Substring(directoryPath.Length + 1);
Console.WriteLine(fileName);
}
There are so many ways :)
1st Way:
string[] folders = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
string jsonString = JsonConvert.SerializeObject(folders);
2nd Way:
string[] folders = new DirectoryInfo(yourPath).GetDirectories().Select(d => d.Name).ToArray();
3rd Way:
string[] folders =
new DirectoryInfo(yourPath).GetDirectories().Select(delegate(DirectoryInfo di)
{
return di.Name;
}).ToArray();
You can simply use linq
Directory.EnumerateFiles(LoanFolder).Select(file => Path.GetFileName(file));
Note: EnumeratesFiles is more efficient compared to Directory.GetFiles as you can start enumerating the collection of names before the whole collection is returned.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetNameOfFiles
{
public class Program
{
static void Main(string[] args)
{
string[] fileArray = Directory.GetFiles(#"YOUR PATH");
for (int i = 0; i < fileArray.Length; i++)
{
Console.WriteLine(fileArray[i]);
}
Console.ReadLine();
}
}
}