Merging namespaces in C# - c#

How can I merge the same namespaces that are scattered over different files in to one file?
I am using Resharper but it doesn't seem to have this option.
Order is not important.
Something like: copy *.cs output.cs but this doesn't merge namespaces.

Here is the code to join the namespaces. I did not put in a duplicate line checker because you may have different classes that may cointain identical lines. Though, LIke all the comments, i dont think its a good idea to have so many classes in one namespace. Its like haveing 500 woman in one house. None the less, Just change the file extension to .cs and your IDE will tell you the duplicate names and remove them. It should take about 2 minutes if you do find and edit all that meet search criteria.
here is the codeL
class Program
{
static void Main(string[] args)
{
StreamReader reader;
StreamWriter writer = new StreamWriter(/*where you want the final txt to be saved. rename the extension to .cs */);
string line;
int count = 0;
string[] fileEntries = Directory.GetFiles(/*where your cs files are*/");
foreach (string fileName in fileEntries)
{
// do something with fileName
File.Copy( fileName, /* location to save the now txt .cs files */ + count.ToString() + ".txt");
count += 1;
}
string[] Completetxt = Directory.GetFiles(/*location where you saved the txt files */);
foreach (string TxtFile in Completetxt)
{
reader = new StreamReader(TxtFile);
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
writer.WriteLine(line);
}
reader.Close();
}
}
}
Just remember this copies all the cs files into one file with all the imports below each other as well as namespace names. Just use your IDE to find the copies and delete them.
Best of luck

Related

How can I store many txt files in order to be embedded in the source code without being visible to the user?

I'm a blind person and I'm trying to create a win form app that aims to help people with visual impairments to learn better the keyboard. There are different levels in this program. such as: match characters, match words and match sentences. Almost I finished everything, but I miss the technique of storing txt files in the source code in order to be invisible to the user in the program files.
Any suggestion?
You can use the StreamWriter method.
https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter?view=net-7.0
A complete example:
internal class Program
{
static void Main(string[] args)
{
// Get the directories currently on the C drive.
DirectoryInfo[] cDirs = new DirectoryInfo(#"c:\").GetDirectories();
// Write each directory name to a file.
using (StreamWriter sw = new StreamWriter("Demo.txt"))
{
foreach (DirectoryInfo dir in cDirs)
{
sw.WriteLine(dir.Name);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("Demo.txt"))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}

Find a string in a zipped file without unzipping the file

Is there a way to search for a string within a file(s) within a zipped folder WITHOUT unzipping the files?
My situation is I have over 1 million files zipped by months of the year.
For example 2008_01, 2008_02, etc.
I need to extract/unzip only the files with specific serial numbers within the files.
The only thing I can find is unzipping the data to a temporary location to perform that search, but it takes me 45-60 minutes just to unzip the data manually. So I assume the code would take just as long to perform that task, plus I don't have that much available space.
Please Help.
Unfortunately, there isn't a way to do this. The zip format maintains an uncompressed manifest that shows file names and directory structure, but the contents of the files themselves are compressed, and therefore any string inside a file won't match your search until the file is decompressed.
This same limitation exists with just about any general-purpose file compression format (7zip, gzip, rar, etc.). You're essentially reclaiming disk space at the expense of CPU cycles.
Using some extension methods, you can scan through the Zip files. I don't think you can gain anything by trying to scan a single zip in parallel, but you could probably scan multiple zip files in parallel.
public static class ZipArchiveEntryExt {
public static IEnumerable<string> GetLines(this ZipArchiveEntry e) {
using (var stream = e.Open()) {
using (var sr = new StreamReader(stream)) {
string line;
while ((line = sr.ReadLine()) != null)
yield return line;
}
}
}
}
public static class ZipArchiveExt {
public static IEnumerable<string> FilesContain(this ZipArchive arch, string target) {
foreach (var entry in arch.Entries.Where(e => !e.FullName.EndsWith("/")))
if (entry.GetLines().Any(line => line.Contains(target)))
yield return entry.FullName;
}
public static void ExtractFilesContaining(this ZipArchive arch, string target, string extractPath) {
if (!extractPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
extractPath += Path.DirectorySeparatorChar;
foreach (var entry in arch.Entries.Where(e => !e.FullName.EndsWith("/")))
if (entry.GetLines().Any(line => line.Contains(target)))
entry.ExtractToFile(Path.Combine(extractPath, entry.Name));
}
}
With these, you can search a zip file with:
var arch = ZipFile.OpenRead(zipPath);
var targetString = "Copyright";
var filesToExtract = arch.FilesContain(targetString);
You could also extract them to a particular path (assuming no filename conflicts) with:
var arch = ZipFile.OpenRead(zipPath);
var targetString = "Copyright";
arch.ExtractFilesContaining(targetString, #"C:\Temp");
You could modify ExtractFilesContaining to e.g. add the year-month to the file names to help avoid conflicts.

Reading multiple .csv files C#

I've a program where i need to read in multiple .csv files from a directory, take some info from each one and then create one large .csv file. However i'm having problems reading them in but not sure why. I have this piece of code in my main method:
string sourceDirectory = #"sourceDirectory/test";
var csvFiles = Directory.EnumerateFiles(sourceDirectory, "*.csv", SearchOption.AllDirectories);
foreach (string currentFile in csvFiles)
{
readFile(currentFile);
}
And then the following in my readFile method:
public static void readFile(string currentFile)
{
StreamWriter writer = new StreamWriter(#"destinationFile.csv");
StreamReader reader = new StreamReader(currentFile);
while(**){
object[] array;
array = new object[11];
array[0] = info1;
array[1] = info2;
array[2] = info3;
//........
writer.WriteLine(string.Join(", ", array));
}
reader.DiscardBufferedData();
writer.Close();
reader.Close();
Without the while loop it only reads in one line of the file, understanably. I can't seem to understand what or even if the while loop should contain. If it was a .txt file i would simply put while ((line = reader.ReadLine()) != null). My code never seems to read in more than one .csv file from the direcotry but there are 6 .csv files in there.
The only data i really need from them is to count certain lines between dates(one of the .csv columns).

Enumerate zipped contents of unzipped folder

I am trying to enumerate the zipped folders that are inside an unzipped folder using Directory.GetDirectories(folderPath).
The problem I have is that it does not seem to be finding the zipped folders, when I come to iterate over the string[], it is empty.
Is Directory.GetDirectories() the wrong way to go about this and if so what method serves this purpose?
Filepath example: C:\...\...\daily\daily\{series of zipped folder}
public void CheckZippedDailyFolder(string folderPath)
{
if(folderPath.IsNullOrEmpty())
throw new Exception("Folder path required");
foreach (var folder in Directory.GetDirectories(folderPath))
{
var unzippedFolder = Compression.Unzip(folder + ".zip", folderPath);
using (TextReader reader = File.OpenText(unzippedFolder + #"\" + new DirectoryInfo(folderPath).Name))
{
var csv = new CsvReader(reader);
var field = csv.GetField(0);
Console.WriteLine(field);
}
}
}
GetDirectories is the wrong thing to use. Explorer lies to you; zip files are actually files with an extension .zip, not real directories on the file system level.
Look at:
https://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive.entries%28v=vs.110%29.aspx (ZipArchive.Entries) and/or
https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile%28v=vs.110%29.aspx (ZipFile) to see how to deal with them.

How to read multiple files from server into c#

I want to know how to read multiple (about 500-1000) text files which are located on a server.
So far, I've written code for a program that only reads a single text file.
Here's how I'm currently reading a single file.
public void button1_Click(object sender, EventArgs e)
{
// Reading/Inputing column values
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] fileLines = File.ReadAllLines(ofd.FileName);
I would like to get rid of the open file dialog box, and let the program automatically read the 500-1000 text files where are located in the sever.
I'm thinking something along the lines of
for (int i =0; i<numFiles; i++)
{
//just use string[] fileLines =File.ReadAllLines()
//how would i specify the path for multiple files?
}
Questions are then:
How would I approach this?
How exactly should I get the number of files?
(I'm guessing I'd have to read the server file which contains them.)
You can use Directory.GetFiles(string path) to get all files from a certain directory. You can then use a foreach loop to iterate through all the files in that directory and do your processing.
You can use recursion to loop through all directories. Using Directory.EnumerateFiles also allows you to use a foreach loop so you don't have to worry about the file count.
private static void ReadAllFilesStartingFromDirectory(string topLevelDirectory)
{
const string searchPattern = "*.txt";
var subDirectories = Directory.EnumerateDirectories(topLevelDirectory);
var filesInDirectory = Directory.EnumerateFiles(topLevelDirectory, searchPattern);
foreach (var subDirectory in subDirectories)
{
ReadAllFilesStartingFromDirectory(subDirectory);//recursion
}
IterateFiles(filesInDirectory, topLevelDirectory);
}
private static void IterateFiles(IEnumerable<string> files, string directory)
{
foreach (var file in files)
{
Console.WriteLine("{0}", Path.Combine(directory, file));//for verification
try
{
string[] lines = File.ReadAllLines(file);
foreach (var line in lines)
{
//Console.WriteLine(line);
}
}
catch (IOException ex)
{
//Handle File may be in use...
}
}
}
Also note Directory.EnumerateFiles provides overload that lets you provide a search pattern to narrow the scope of the files.
How you go about getting your files depends on if they are all located in the same directory of if you'll need to recursively search through a directory and all child directories. Directory.GetFiles is where you want to start. It has 3 overloads seen here. So you might try something like this:
string path = "\mypath\tosomehwere";
string searchPattern = "*.txt";
string[] MyFiles = Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories);
Then just loop through the string array and proccess each file as you would normally.
foreach (string filePath in MyFiles)
{
MyFileProcessMethod(filePath)
}
Path.GetFileName(filePath) will return the individual text file name should you need it for your processing requirements.

Categories