C# File.Move firewall port - c#

I need to copy and/or move files across servers to the other side of my
firewall. I was wondering if anyone can tell me what port(s) I will need to
open to run these methods in my C# program?
class MoveIt
{
public static void Main()
{
var localPath = #"c:\temp\";
var remotePath = #"\\MyRemoteServer\MyShare\MyPath\"
try
{
if (File.Exists(localPath + "MyTestFile.txt") &&
Directory.Exists(remotePath))
{
File.Move(localPath + "MyTestFile.txt", remotePath +
"MyTestFile.txt");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}

You need at least TCP 445, and to be sure you also want TCP 137-139, though this latter group is only if you're still stuck using NetBIOS for smb name resolution.

Related

C# create firewall rule to allow system to respond to pings?

I inherited a C# application and working on it. It creates some firewall rules programmatically. By default it disables everything on a specific interface, then allows a few specified TCP ports access, which is fine. I can't figure out how to modify the code to allow that port to respond to ping commands. However, and couldn't find any code online in other searches that would do that.
Does anyone know how to use C# to create a firewall rule to allow a port to respond to ping commands? The app will be deployed in Windows 7 embedded, 64 bit.
Here is some existing code which creates a rule to open a TCP port, which works OK:
private void SetupFirewallAllowIncomingRule(int port)
{
try
{
_log.Debug("Creating instance of Windows Firewall policy (HNetCfg.FwPolicy2)...");
INetFwPolicy2 firewallPolicy = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")) as INetFwPolicy2;
if (null == firewallPolicy)
{
_log.Error("HNetCfg.FwPolicy2 instance could not be created!");
return;
}
string name = "Rule Port " + port.ToString();
foreach (INetFwRule2 rule in firewallPolicy.Rules)
{
if (name.Equals(rule.Name))
{
_log.WarnFormat("Windows Firewall Rule ({0}) already exists. It will not be created again.", rule.Name);
return;
}
}
_log.Debug("Creating new Windows Firewall Rule (HNetCfg.FWRule)...");
INetFwRule firewallRule = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")) as INetFwRule;
if (null == firewallRule)
{
_log.Error("HNetCfg.FWRule instance could not be created!");
return;
}
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.Name = name;
firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
//NOTE: Must do this after setting the Protocol!
firewallRule.LocalPorts = port.ToString();
_log.DebugFormat("Adding Windows Firewall Rule {0}...", firewallRule.Name);
firewallPolicy.Rules.Add(firewallRule);
_log.InfoFormat("Windows Firewall Rule {0} added.", firewallRule.Name);
}
catch (Exception ex)
{
_log.Error("Windows Firewall Rule could not be added for port " + port.ToString() + "!", ex);
}
}

Connecting to another PC in LAN via sockets in C#

So I'm trying to connect to another PC via TCP protocol using sockets, 192.168.1.72 is another PC's address, however, I'm not relly sure im going the right road. I have server also oon different computer, and theese two programs seem to work well on same computer, when in line with _clientSocket.Connect();, i use IPAdress.Loopback instead o host. Am I doint the right aproach, or should i look elsewhere, and if i am, how can i make this function work, because now it simply crashes and indicates there is something wrong with host declaration
private static void LoopConnect()
{
IPAddress host = new IPAddress(Encoding.ASCII.GetBytes("192.168.1.72"));
int attempts = 0;
while(!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(host, 100);
}
catch (SocketException)
{
Console.Clear();
Console.WriteLine("Connection attempts: " + attempts.ToString());
}
}
Console.Clear();
Console.WriteLine("Connected");
}
If you supply the IP adddress as a string, you need to use the static Parse method:
IPAddress host = IPAddress.Parse("192.168.1.72");

Something is deleting a console app. Why is it being deleted?

I need to learn how to use SMO within a C# program, so the first thing I did was start a new, console app and then began putting in the basics. I decided to make the app accept parameters so I can pass in things like usernames, logins, etc. As I work on it and build it I have a PowerShell window open where I can call the app, give it parameters or not, etc. But something weird is happening which I don't understand. Sometimes when I run the app in the PowerShell window, it's then deleted for some reason. Why is it doing that? I discovered it when it first gave me the following error message:
Program 'SmoListLogins.exe' failed to run: The system cannot find the file specifiedAt line:1 char:1 + .\SmoListLogins.exe "MYCOMPANY\Rod"
My SmoListLogins.exe program isn't there. Naturally I can easily re-create it, but I don't understand why its being deleted.
So you can see what I'm working with, here's the source code. I took it from a MSDN article and have added a little bit:
using System;
using System.Data;
using Microsoft.SqlServer.Management.Smo;
namespace SmoListLogins
{
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
var userName = args[0];
ListLogins(userName);
}
else
{
ListLogins();
}
}
static private void ListLogins(string userName = "")
{
var userNamePassed = (userName != "");
Server srv = new Server("YOURSQLINSTANCE");
//Iterate through each database and display.
foreach (Database db in srv.Databases)
{
Console.WriteLine("========");
Console.WriteLine("Login Mappings for the database: " + db.Name);
Console.WriteLine(" ");
//Run the EnumLoginMappings method and return details of database user-login mappings to a DataTable object variable.
DataTable d;
try
{
d = db.EnumLoginMappings();
//Display the mapping information.
foreach (DataRow r in d.Rows)
{
var userNameMatches = false;
var starting = true;
foreach (DataColumn c in r.Table.Columns)
{
if (!userNamePassed)
{
Console.WriteLine(c.ColumnName + " = " + r[c]);
}
else
{
if (starting)
{
starting = false;
if (userName == r[c].ToString())
{
userNameMatches = true;
}
}
if (userNameMatches)
{
Console.WriteLine(c.ColumnName + " = " + r[c]);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error processing database: {db.Name}");
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine();
}
}
}
}
}
I believe I now know what was deleting my executable. It wasn't something I thought of, so I'm sharing with everyone the answer. Today I got an email from our chief security officer, informing me that the program I wrote was being blocked by Symantec Endpoint Protection. In my testing I'd run my app over and over again. After a few iterations of that it would disappear. It didn't occur to me that it was our corporate AV that might be doing it. Now it looks as though that is exactly what was going on.
Thank you everyone for your input in trying to help me resolve this. I hope that if anyone else encounters this problem they might consider the possibility of their AV as the reason why the app they wrote disappears.

Ping to server for external connectivity

I have a c# application that has a module for checks the server connection. The relevant code is like the following:
private void PingCheck(string hostName)
{
using (var p = new Ping())
{
try
{
var pr = p.Send(hostName, 2000);
if (pr.Status != IPStatus.Success)
{
log.ErrorFormat("Ping error! Host = {0}, Ping status = {1}", hostName, pr.Status.ToString());
}
}
catch (Exception exc)
{
log.Error("Ping error!", exc);
}
}
}
We have deployed this application to our server that is inside the same network as the target machine. That's why this method checks internal connectivity. Is there any way to check server external connectivity? Because sometimes server connection is available in our network although connection from external network is down. How can I achieve this?
No, there is not, since you are on the server itself.
Either ping some resource outside to check connectivity, or use the NetworkInterface.GetIsNetworkAvailable() method to check whether there is an active connection.

How to delete a shared folder using c# code if the directory is opened on another machine?

I'm trying to delete an empty shared directory which is opened in another machine.
If i directly delete the directory(right click and delete) it is removed.
Stopwatch st = new Stopwatch();
st.Start();
while(true){
try
{
Directory.Delete(pathToDelete, true);
Console.WriteLine("Directory Deleted" + "Elapsed time:" + st.Elapsed.Seconds.ToString() + "sec");
break;
}
catch (Exception e)
{
if ((e is System.IO.IOException) || (e is System.UnauthorizedAccessException) ||
(e is System.Reflection.TargetInvocationException))
{
Console.WriteLine(e.ToString());
if (st.Elapsed > TimeSpan.FromMinutes(5))
{
Console.WriteLine("Can not delete directory ");
return;
}
Thread.Sleep(1000);
}
else
{
throw;
}
}
}
It is not deleting the directory if the directory opened on same machine or different machine using the shared-path.
I found this
but i couldn't understand the code properly.
Anyone suggest a better method?
Thanks in Advance
System.IO.IOException: The process cannot access the file 'c:\dir' because it is being used by another process
That means that its in use, therefore your not going to be able to remove it. If its empty like you say, then it must be either a) in use by someone on the Network Share or there's something running on the server that its ran from that's monitoring it. You may need to stop a service.

Categories