How to share and unshare windows folder using c# - c#

I have to share a folder to a user and unshare it programmatically using c#.
I am able to share a folder using InvokeMethod of Win32_Share class.
int IsShared = 0;
ManagementClass mc = new ManagementClass("Win32_Share");
object[] methodargs = { folderPath, shareName, "0" };
object result = mc.InvokeMethod("Create", methodargs);
if ((uint)result != 0)
{
IsShared = 1;
return IsShared;
}
else
return IsShared;
But how to do it for a particular user?
Also please let me know how to unshare it? Win32_Share class has delete() method.But I am unable to unshare using it.

Maybe not the best approach, but I ended up calling a command line silently and it worked for me:
To share:
var folderName = "your_shared_folder_name";
var targetDir = "your_folders_target_path";
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
CreateNoWindow = true,
ErrorDialog = false,
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
Arguments = $"/C net share {folderName}=\"{targetDir}\" /Grant:Everyone,READ"
};
process.Start();
process.WaitForExit();
Notice the /Grant:Everyone,READ. This is what I wanted, but you might wanna fiddle with this part a little bit.
To delete:
var folderName = "your_shared_folder_name";
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
CreateNoWindow = true,
ErrorDialog = false,
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
Arguments = $"/C net share \"{folderName}\" /delete"
};
process.Start();
process.WaitForExit();

Check the following
private void shareDir(string p)
{
string shareName = "testshare";
string shareDesc = "This is a test share kekelar2000";
string path = p;
SHARE_INFO_502 info = new SHARE_INFO_502();
info.shi502_netname = shareName;
info.shi502_type = SHARE_TYPE.STYPE_DISKTREE;
info.shi502_remark = shareDesc;
info.shi502_permissions = 0; // ignored for user-level security
info.shi502_max_uses = 1;
info.shi502_current_uses = 1;
info.shi502_path = path;
info.shi502_passwd = null; // ignored for user-level security
info.shi502_reserved = 0;
info.shi502_security_descriptor = IntPtr.Zero;
uint error = 0;
uint result = NetShareAdd(Dns.GetHostName(), 502, ref info, out error);
}

Related

Not possible to set input file in linux command running from .NET Core

I'm running .NET Core app on the linux docker container
When I call the command from the linux terminal it works well:
./darknet detector test -out result.json < data/file-list.txt
But when I start the process from the .NET Core I see error. Process runner method:
public static string RunCommand(string command, string args)
{
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = command,
Arguments = args,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
process.Start();
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
return #$"{output}{Environment.NewLine}-------------------------------{Environment.NewLine}{error}";
}
Calling code:
string args = #$"detector test -out result.json < data/file-list.txt";
string output = ProcessRunner.RunCommand("./darknet", args);
Here is the part of the output:
Cannot load image "<"
STB Reason: can't fopen
How to fix it?
You can write the process's standard input once you set the RedirectStandartInput to true while starting your process. Here is an example how to write :
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "./ConsoleApp1.exe",
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true, // here you need
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
using var file = File.OpenRead("./1.txt");
using var reader = new StreamReader(file);
while (true)
{
var line = await reader.ReadLineAsync();
if (string.IsNullOrWhiteSpace(line)) break; // you can use some other stoping decision
await process.StandardInput.WriteLineAsync(line);
}

How to pass password StandardInput to pg_dump?

I'm creating Process to run pg_dump.exe in C#
var processStartInfo = new ProcessStartInfo
{
Arguments = #"-U postgres -W -f D:\postgres\test123_dump.sql postgres",
CreateNoWindow = true,
FileName = #"C:\PostgreSQL\bin\pg_dump.exe",
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardInput = true
};
Process process = new Process() { StartInfo = processStartInfo, EnableRaisingEvents = true };
process.Start();
using( StreamWriter sw = process.StandardInput)
{
sw.WriteLine("123"); // test password
};
It will run pg_dump.exe, it will show prompt to pass the password, but StreamWriter seems to not work for some reason.
You could use this string to put your authentication info directly in argument list
var processStartInfo = new ProcessStartInfo
{
Arguments = #"--dbname=postgresql://user_name:pass_word#Localhost:5432/bd_name_to_save -F c -b -f output_bd_name",
CreateNoWindow = true,
FileName = #"C:\PostgreSQL\bin\pg_dump.exe",
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardInput = true
};
Process process = new Process() { StartInfo = processStartInfo, EnableRaisingEvents = true };
process.Start();

How to Execute multiple commands in Process

I have a list of a thousand items, Each of these items must be checked by the CMD.exe, With the help of the following code, I can check an item by CMD
var p = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
FileName = "cmd",
Arguments = $"list {Id}"
}};
p.Start();
var _Data = await p.StandardOutput.ReadToEndAsync();
But the question is, I want all of these items to be checked quickly by CMD, I'm currently doing this as follows
foreeach(var item in list)
{
var p = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
FileName = "cmd",
Arguments = $"list {item}"
}};
p.Start();
var _Data = await p.StandardOutput.ReadToEndAsync();
}
But it takes a long time to do this
You can redirect standard input and use a StreamWriter to write to it:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("mysql -u root -p");
sw.WriteLine("mypassword");
sw.WriteLine("use mydb;");
}
}

.NET Intercepted STDOUT from Python is always empty in Unity

I'm trying to use a Python program to send a continuous stream of information from one program to another, like this question, but in byte form.
pythonPath and pythonScript are just the file locations of the script and python.exe.
C# code
public static void PythonKernel_Test() {
Process pythonProcess = Process.Start(new ProcessStartInfo() {
FileName = pythonPath,
Arguments = pythonScript,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true
});
Stream pythonStdOut = pythonProcess.StandardOutput.BaseStream;
for (int i = 0; i < 1000; i++) {
byte[] buffer = new byte[256];
pythonStdOut.Read(buffer, 0, 256);
Debug.Log(Encoding.ASCII.GetString(buffer) + Environment.NewLine + BitConverter.ToString(buffer));
}
pythonStdOut.Close();
}
Although this is in Unity, you could just substitute Debug.Log for Console.WriteLine().
However, even though I am spamming stdout with SYNC, nothing appears on the C# side. It does however, appear in the command prompt when ran from shell.
Python code
w = sys.stdout.buffer
while True:
w.write(b"SYNC\n")
sys.stdout.flush()
Here a working sample to try out
public static void PythonKernel_Test()
{
var pi = new ProcessStartInfo
{
FileName = "python",
Arguments = "test.py",
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
};
var pythonProcess = new Process
{
StartInfo = pi,
};
pythonProcess.OutputDataReceived+= (s,e) =>
{
Console.WriteLine("OUT: {0}",e.Data);
};
pythonProcess.ErrorDataReceived+= (s,e) =>
{
Console.WriteLine("ERR: {0}",e.Data);
};
pythonProcess.Start();
pythonProcess.BeginOutputReadLine();
pythonProcess.BeginErrorReadLine();
pythonProcess.WaitForExit();
}
It will read the output asynchronously
Taken from https://stackoverflow.com/a/29753402/1744164
test.py
import sys
while True:
sys.stdout.write(b"SYNC\n")
sys.stdout.flush()

use mongodb_name does not work in C# Process

I regular use command
use some_mongodb
to create new database from command prompt on windows
it seems that this command does not work when you want to execute this in C# process
I have the following code trying to create mongo database from C#
ProcessStartInfo startInfo = new ProcessStartInfo
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
WorkingDirectory = _mongoBinDir,
FileName = "mongo.exe",
Arguments = "use " + databaseTxt.Text
};
_mongoInsertProcess = new Process
{
StartInfo = startInfo
};
_mongoInsertProcess.Start();
string stderrStr = _mongoInsertProcess.StandardError.ReadToEnd();
string stdoutStr = _mongoInsertProcess.StandardOutput.ReadToEnd();
stdoutStr variable get value
"MongoDB shell version: 3.2.1 connecting to: use
2016-04-07T15:28:52.875+0200 E - [main] file [some_db] doesn't
exist failed to load: some_db"
Please advise on this.
use some_db isn't a valid argument. Just pass the name of the database i.e:
ProcessStartInfo startInfo = new ProcessStartInfo
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
WorkingDirectory = _mongoBinDir,
FileName = "mongo.exe",
Arguments = databaseTxt.Text
};

Categories

Resources