Fail to make directory in C# - c#

Below is my code to create a directory in my PC.
using System;
using System.IO;
using System.Text;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo dataDir = new DirectoryInfo(#"C:\CsharpData");
Console.WriteLine(dataDir.Attributes);
Console.ReadLine();
}
}
}
But, the result looks like this.
Attribute is equal to -1, and I can't get my desired directory.
Can anyone let me know what my mistake is?

Use below code. You need to use create ,ethod for creating the directory.
DirectoryInfo dataDir = new DirectoryInfo(#"C:\CsharpData");
if(!dataDir.Exists)
{
dataDir.Create();
}
System.Console.WriteLine(dataDir.Attributes);
System.Console.ReadLine();

Related

UnRAR DLL unable to be referenced in C#

I was trying to make a program to clean out some directories on my NAS and I noticed that a lot of folders contained nested rar and zip files and I have plenty of space to unpack them. The program should ask the user for a directory to be cleaned then unpack all rars then delete all of the rars. I'm trying to use UnRAR DLL and I cant even get the rars to unpack. I realize I'm having an issue where visual studio 2022 is refusing to recognize the Unrar DLL in the "using" command. Because of that I've been unable to unpack a single file. This is one my first useful programs so if im missing something basic I understand.
This is my initial attempt:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using UnRAR;
namespace Cleaning
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter Directory To Be Cleaned");
string rar_path = Console.ReadLine();
string[] Rars = Directory.GetFiles(rar_path, "*.rar", SearchOption.AllDirectories);
foreach (string rar in Rars)
{
string source = rar;
string dest = "C:\\Users\\Kaleb\\OneDrive\\Desktop\Test Area";
UnRAR unrar = new UnRAR();
unrar.Password = "password_of_myarchive";
unrar.Open(#source, UnRAR.OpenMode.Extract);
while (unrar.ReadHeader())
{
unrar.ExtractToDirectory(#dest);
}
unrar.Close();
}
}
}
}
For reference I have added the UnRAR DLL to the project folder.
SO I was able to get it working with the source code from the great people over at SharpCompress and utilizing their source I've got the following stable build.
using SharpCompress.Archives;
using SharpCompress.Archives.Rar;
using SharpCompress.Common;
using System;
using System.IO;
using System.Linq;
using System.Globalization;
namespace ConsoleApp3
{
public class Program
{
static void Main(string[] args)
{
for (; ; )
{
Console.WriteLine("Enter E to extract all directories in file path");
Console.WriteLine("Enter D to delete all Archives in file path");
Console.WriteLine("REMEMBER TO ALWAYS EXTRACT BEFORE DELETING");
string option = Console.ReadLine();
if (option == "e" || option == "E")
{
Console.WriteLine("Enter Directory To Be Cleaned");
//as a warning this will extract all files from any rar in the slected driectory one at a time in order.
//if a rar is broken it will halt the program until the offendin rar is deleted best way to find is to see what has been extracted so far and go from there
//or one could also limit the directory in order to refine the number of rars to look for
string rar_path = Console.ReadLine();
string[] Rars = Directory.GetFiles(rar_path, "*.rar", SearchOption.AllDirectories);
foreach (string rar in Rars)
{
var DirectoryFinal = Path.GetDirectoryName(rar);
using (var archive = RarArchive.Open(#rar))
{
foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
{
entry.WriteToDirectory(#DirectoryFinal, new ExtractionOptions()
{
ExtractFullPath = true,
Overwrite = true
});
}
};
}
}
else if (option == "d" || option == "D")
{
Console.WriteLine("Enter Directory To Be Cleaned");
//be careful with this i would recomend extracting and then chekcing everything first
string rar_path = Console.ReadLine();
string[] TobeDeleted = Directory.GetFiles(rar_path, "*.r*", SearchOption.AllDirectories);
foreach (string rarstobedeleted in TobeDeleted)
{
File.Delete(rarstobedeleted);
}
}
else
{
Console.WriteLine("Thats not an option try again");
}
Console.WriteLine("Cleaning Complete.");
;
}
}
}
}
This work effectively for rar files only for the time being but will effectively clean up any directories where someone may have downloaded a large amount of files stored in separated rars

How to pass a filename/path to text parser

I'm trying to get a simple text parser class to work in VS2015. I received the class code and built a basic Console Application, added the class Cawk and tried to compile/run it.
The main error that I get is
Argument 1: cannot convert from 'string' to 'System.IO.StreamReader'
It's clear that I can't figure out how to pass a filename through Main to Cawk. How do I give it an argument of a filename?
Any help or pointers would be appreciated.
My Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main()
{
string input = #"c:\temp\test.txt";
Cawk.Execute(input);
}
}
}
Snippet of My Cawk.cs:
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication3
{
public static class Cawk
{
public static IEnumerable<Dictionary<string, object>> Execute(StreamReader input)
{
Dictionary<string, object> row = new Dictionary<string, object>();
string line;
//string[] lines = File.ReadAllLines(path);
//read all rows
while ((line = input.ReadLine()) != null)
{
Execute accepts a StreamReader not a string.
Cawk.Execute(new StreamReader(#"c:\temp\test.txt"))
However, you should close the stream after you are done with it.
using (var sr = new StreamReader(#"c:\temp\test.txt"))
{
Cawk.Execute(sr);
}
something like:
var sr = new System.IO.StreamReader(#"c:\temp\test.txt");
Cawk.Execute(sr);
Simply use the File class from the System.IO namespace.
Cawk.Execute(File.OpenText(#"c:\temp\test.txt"));
Like this:
string input = #"c:\temp\test.txt";
Cawk.Execute(new System.IO.StreamReader(input));
You can put using System.IO; to the top like the rest of the usings, then you don't have to write it out later.

fetching only one url in c#

I am working on collecting urls from the web site in C# using WatiN framework. In my program it is fetching only one url. I don't know what is the problem. Any help will be appreciated.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WatiN.Core;
using WatiN.Core.Native.InternetExplorer;
namespace magicbricks
{
class scroll
{
[STAThread]
static void Main(string[] args)
{
Browser browserInstance;
browserInstance = new IE(#"http://www.99acres.com/property-in-chennai- ffid?search_type=QS&search_location=CP32&lstAcn=CP_R&lstAcnId=32&src=CLUSTER&isvoicesearch=N&keyword_suggest=chennai%20%28all%29%3B&fullSelectedSuggestions=chennai%20%28all%29&strEntityMap=W3sidHlwZSI6ImNpdHkifSx7IjEiOlsiY2hlbm5haSAoYWxsKSIsIkNJVFlfMzIsIFBSRUZFUkVOQ0VfUywgUkVTQ09NX1IiXX1d&texttypedtillsuggestion=chennai&refine_results=Y&Refine_Localities=Refine%20Localities&action=%2Fdo%2Fquicksearch%2Fsearch&suggestion=CITY_32%2C%20PREFERENCE_S%2C%20RESCOM_R");
foreach (var links in browserInstance.Links.Filter(Find.ByClass("b")))
{
Console.WriteLine(links.Url);
String filePath = "C:/Users/User/Desktop/New folder";
String fileName = "newop4.csv";
using (StreamWriter sr = new StreamWriter(Path.Combine(filePath, fileName), true))
{
sr.WriteLine(links.Url);
}
Console.ReadLine();
}
}
}
}
the above code prints only one url in the console.
Remove the Console.ReadLine(); As you are in a ForEach loop. If you still want the Console.ReadLine(); move it out the foreach
The Console.ReadLine(); waits for a user input, after you enter any value you should see the next URL.

Getting and using current directory in c# script

This is just a sample, but it will help illustrate what I'm trying to do.
I know how to get the current directory as shown in the script below, and I can can set a file variable.
The problem I'm having is that I can't figure out how to make it create a folder and put the file in the folder
For example (using the variables below)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var cd = Directory.GetCurrentDirectory();
Directory.CreateDirectory(cd: \5app\);
File.Copy(c:\xyz.txt, cd: \5app\xyz.txt
}
}
}
I know what I have written above is not correct because vs10 tells me so, but doesn't give me very much help.
You're missing a parenthesis and a semicolon, and, especially, arguments of methods Directory.CreateDirectory() and File.Copy() are strings, put them inside quotes:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var cd = Directory.GetCurrentDirectory();
Directory.CreateDirectory(cd + #"\5app\");
File.Copy(#"c:\xyz.txt", cd + #"\5app\xyz.txt");
}
}
}
MSDN references: Directory.CreateDirectory, File.Copy
Thanks to Cole Johnson for pointing out that it shouldn't be #"cd: \5app\".
You don't use quotes.
In addition, I recommend against explicit parameter naming. If you look at the CIL generated when using explicit parameters, there is a performance downgrade as the parameter variables are saved to a local variable, then passed. This results in an unneeded strfld command.
There are several problems with your code, which Compiler Errors will likely help you to unravel:
The method Directory.CreateDirectory(string path) requires a string, which is encased in "".
Here is an MSDN article on how to use Directory.CreateDirectory
Same with the method File.Copy(string source, string destination)
Here is an MSDN article on how to use File.Copy
Since Directory.GetDirectory() returns a string, you can just concatinate your specific directory to the result. But remember to use proper Escape Sequences in your strings for things like Backslash.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string cd = Directory.GetCurrentDirectory();
Directory.CreateDirectory(cd + "\\5app\\");
File.Copy("c:\\xyz.txt", cd + "\\5app\\xyz.txt");
}
}
}

System.Diagnostics.Process.Start() opens/runs wrong directory?

I think I found a bug. In my opinion Process.Start runs wrong directory.
To test, create default console application template and paste following:
using System;
using System.Diagnostics;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
bool test = false;
DirectoryInfo root = Directory.CreateDirectory(
System.IO.Path.Combine(Directory.GetCurrentDirectory(), "folder"));
DirectoryInfo bug = Directory.CreateDirectory(
System.IO.Path.Combine(root.FullName, "bug"));
DirectoryInfo bugDotCom = Directory.CreateDirectory(
System.IO.Path.Combine(root.FullName, "bug.com"));
ProcessStartInfo bugPSI = new ProcessStartInfo(bug.FullName);
ProcessStartInfo bugDotComPSI = new ProcessStartInfo(bugDotCom.FullName);
if (test)
{
Console.WriteLine(bug.FullName);
Process.Start(bugPSI);
}
else
{
Console.WriteLine(bugDotCom.FullName);
Process.Start(bugDotComPSI);
}
Console.ReadKey();
}
}
}
when variable test is set to false, bug.com directory should be opened, otherwise bug directory. However, this example shows that always bug.com is opened (no matter to test variable) - at least for me.
What's wrong? I'm missing something or that's just a bug?
.com is part of %PATHEXT%, so Windows will use it if it exists.
Changing the extension so that there is no bug.com folder avoids the problem.
To fix the problem, add a \ to the end of the path.

Categories

Resources