File.Copy from local to shared folder in server - c#

I'm having problems when copying a .txt from a local server ("D:\AuditFiles") to a shared folder in another server ("\\PrintServer\SharedFolder"). It throws the exception:
"The filename, directory name, or volume label syntax is incorrect."
I thought it could be something with the path format, so I tried by adding to the server path an #:
#Configuration.Manager["Path"] | #"\\ServerPath\SharedFolder"
I've also tried with this format: \\ServerPath\SharedFolder... None of them worked.
By the way its not an access problem, cause i've tried to do the same thing running a command prompt from within c#:
System.Diagnostics.Process.Start("cmd.exe", "/C COPY PATH1, PATH2"); //This worked and copied the file.
I'd be greatful if someone could give me a clue of what could be the problem here. At least an advice of what to do.
Thanks in advance and sorry me bad english!
Edit:
This is the part of the code that should work:
string pathPrevDay = "D:\AuditFiles\enc_" + svr.Name + "_counts" + day.AddDays(-1).ToString("dd-MM-yy") + ".txt";
if(File.Exists(pathPrevDay))
{
File.Copy(pathPrevDay, #ConfigurationManager.AppSettings["MAIL_SERVER_PATH"]);
}

You need to escape the backslashes and indicate the name of the file in File.Copy(pathPrevDay, ConfigurationManager.AppSettings["MAIL_SERVER_PATH"]);.
Change this:
string pathPrevDay = "D:\AuditFiles\enc_" + svr.Name + "_counts" + day.AddDays(-1).ToString("dd-MM-yy") + ".txt";
to this:
string pathPrevDay = "D:\\AuditFiles\\enc_" + svr.Name + "_counts" + day.AddDays(-1).ToString("dd-MM-yy") + ".txt";
You can also use single slashes (/) instead like this:
string pathPrevDay = "D:/AuditFiles/enc_" + svr.Name + "_counts" + day.AddDays(-1).ToString("dd-MM-yy") + ".txt";

Related

How do I replace PATH Environment variables to double quote + backslashes those which have spaces in C#?

Language version: C# - Operating system: Win 10 - IDE: Visual Studio
I've got a problem when letting the user set a path.
When the path is without spaces, all good. No issues.
When the path is with spaces, the CLI i'm forwarding the data to, doesn't accept it and instantly closes.
That's because it misses the right syntax (double quotes at beginning & end + double backslashes) when it arrives.
So the right syntax is:
app.exe -q MP3_128 -p "C:\\test test\\"
Since I'm using the Environment.GetFolderPath in WMF, I have no clue how to add these to its output...
How do I replace PATH Environment variables to double quote + backslashes those which have spaces in C#?
Code:
if (Settings.Default.download == "")
{
MessageBox.Show("Be sure your download path doesnt contain any spaces!");
String path = Environment.GetFolderPath (Environment.SpecialFolder.MyMusic);
String pathDouble = path.Replace("'", "\"");
Settings.Default.download = #"""C:\\Test\DOWN LOADS""";
Settings.Default.Save();
}
which been reached here in
Code:
if (Settings.Default.sm != "")
{
download.StartInfo.FileName = Settings.Default.sm;
string a = " -q " + qualitys + " -p " + Settings.Default.download + " " +
info[result.SelectedIndex].link;
Debug.Write(a);
download.StartInfo.Arguments = a;
}
The hardcoded default path set works.
But when the user changes that path using the GUI to their own likings, it's gone.
I think I'm editing the wrong code.
This code, I have edited, which only now needs a double \ after the drive:
using (var folderDialog = new FolderBrowserDialog())
{
if (folderDialog.ShowDialog() == DialogResult.OK)
{
Settings.Default.download = #"""" + folderDialog.SelectedPath + #"\\""";
Settings.Default.Save();
txb_download_folder.Text = Settings.Default.download;
}
}
But how?
A simple \ extra in the first #"\" results in \"C:\test test\\".

Copy file to remote location throws network path not found intermittently

I am trying to copy a file generated (Excel file) by my c# code into a remote network path to which I have access as below:
string folder = "\\\\testing-path\\Audit\\Reports";
if (!(Directory.Exists(folder + "\\" + DateTime.Now.ToString("MM-dd-yyyy") + "\\" + "Audit")))
{
Directory.CreateDirectory(folder + "\\" + DateTime.Now.ToString("MM-dd-yyyy") + "\\" + "Audit");
}
folder = folder + "\\" + DateTime.Now.ToString("MM-dd-yyyy") + "\\" + "Audit";
if (File.Exists(folder + "\\Audit- " + fname + ".xlsx"))
{
File.Delete(folder + "\\Audit- " + fname + ".xlsx");
}
string fileName = folder + "\\Audit- " + fname + ".xlsx";
wb.SaveAs(fileName,
Excel.XlFileFormat.xlWorkbookDefault, null, null,
false, false, Excel.XlSaveAsAccessMode.xlNoChange,
null, null, null, null, null);
This code works perfectly fine 8/10 times and throws network error (Network path not found) other 2 times. When the remote path throws this error I open the above remote path using run command on the machine I run this code and I am able to access it as normal. Closing the folder opened manually and re-running the code is solving the issue. What could be the issue? Am I doing something wrong here?
PS: I also tried to save the excel file onto desktop and then use File.Copy and there is no change to this intermittent behaviour.
Check the following things
1) First you have to check whether machine is on or off
2) Then check you have access rights to put the file in that particular folder and dont
put it inside ' C ' Drive because C is not accessible for other users in network put it inside D or E drive.
3) If Folder is Missing You have to Create A Folder first
and what is ' WB '
if(!Directory.Exists("\\\\testing-path\\Audit\\Reports"))
Directory.Create("\\\\testing-path\\Audit\\Reports");
Use
FilePath Byte
File.ReadAllBytes("FilePath/FileName.Extension",byte) // D:\\Test.xls,12878
then in Remote Location
FilePath Byte
File.WriteAllBytes("FilePath/FileName.Extension",byte)// D:\\Test123.xls,12878
Check this Link
Accessing paths in Remote Machine : http://www.codeproject.com/Questions/184633/Connect-to-a-shared-folder-using-ip-address-in-vb6

Java (Minecraft) doesnt start from c#

When I copy paste the javaw.exe -arguments to console it works but, when I launch it like this it doesn't work.
string directory = "C:\\Users\\Can\\AppData\\Roaming\\.minecraft";
string java = #"C:\windows\system32\javaw.exe";
string javaLocation = "C:\\Program Files\\Java\\jre7\\bin\\javaw.exe";
string RAM = "1G";
string username = "namehere";
string token = "--session token:"+tokenGenerated;
string version = "1.6.2";
string launch = "-Xmx" + RAM + " -Djava.library.path={0}\\versions\\1.6.2\\1.6.2-natives-7453523379463 -cp {0}\\libraries\\net\\sf\\jopt-simple\\jopt-simple\\4.5\\jopt-simple-4.5.jar;{0}\\libraries\\com\\paulscode\\codecjorbis\\20101023\\codecjorbis-20101023.jar;{0}\\libraries\\com\\paulscode\\codecwav\\20101023\\codecwav-20101023.jar;{0}\\libraries\\com\\paulscode\\libraryjavasound\\20101123\\libraryjavasound-20101123.jar;{0}\\libraries\\com\\paulscode\\librarylwjglopenal\\20100824\\librarylwjglopenal-20100824.jar;{0}\\libraries\\com\\paulscode\\soundsystem\\20120107\\soundsystem-20120107.jar;{0}\\libraries\\argo\\argo\\2.25_fixed\\argo-2.25_fixed.jar;{0}\\libraries\\org\\bouncycastle\\bcprov-jdk15on\\1.47\\bcprov-jdk15on-1.47.jar;{0}\\libraries\\com\\google\\guava\\guava\\14.0\\guava-14.0.jar;{0}\\libraries\\org\\apache\\commons\\commons-lang3\\3.1\\commons-lang3-3.1.jar;{0}\\libraries\\commons-io\\commons-io\\2.4\\commons-io-2.4.jar;{0}\\libraries\\net\\java\\jinput\\jinput\\2.0.5\\jinput-2.0.5.jar;{0}\\libraries\\net\\java\\jutils\\jutils\\1.0.0\\jutils-1.0.0.jar;{0}\\libraries\\com\\google\\code\\gson\\gson\\2.2.2\\gson-2.2.2.jar;{0}\\libraries\\org\\lwjgl\\lwjgl\\lwjgl\\2.9.0\\lwjgl-2.9.0.jar;{0}\\libraries\\org\\lwjgl\\lwjgl\\lwjgl_util\\2.9.0\\lwjgl_util-2.9.0.jar;{0}\\versions\\1.6.2\\1.6.2.jar net.minecraft.client.main.Main --username " + username + " " + token + " --version " + version + " --gameDir {0} --assetsDir {0}\\assets";
launch = String.Format(launch, directory);
string text = launch;
// WriteAllText creates a file, writes the specified string to the file,
// and then closes the file.
Directory.SetCurrentDirectory(#"C:\windows\system32\");
Process.Start("javaw.exe",
Path.Combine(launch));
What am I doing wrong?
Why do you need to call Path.Combine if your whole path is in one string?
Assuming your javaw.exe is actually in C:\windows\system32\, Process.Start("java.exe", launch); should work as intended.
Source - Path on MSDN: http://msdn.microsoft.com/en-us/library/system.io.path.aspx
Just use Java's real location instead of "javaw" like "c:\programfiles\Java\jre7\bin\javaw.exe"

Unable to generate file from ASP.NET with inkscape

I have an ASP.NET application on my local machine that works. This application takes an SVG file and creates a PNG from it using inkscape. I have tried to migrate that application to my production server. Oddly, the png creation is not working. The really strange part is, an Exception is not being thrown either. I have taken the command line parameters that are being created and copied and pasted them into the command line environment and they work. For instance, here is the line:
inkscape.exe -f "C:\inetpub\wwwroot\MyTest\sample.svg" -e "C:\inetpub\wwwroot\MyTest\sample.png"
I thought it was something simple, so I extracted the code into a sample web project. This project just converts a .svg to a .png. Once again, it worked in my local environment, but not in the production environment. Here is the code:
protected void executeButton_Click(object sender, EventArgs e)
{
try
{
string sourceFile = Server.MapPath("svg") + "\\" + ConfigurationManager.AppSettings["sourceFile"];
string targetFile = Server.MapPath("png") + "\\" + ConfigurationManager.AppSettings["targetFile"];
string args = "-f \"" + sourceFile + "\" -e \"" + targetFile + "\" -w100 -h40";
string inkscape = ConfigurationManager.AppSettings["inkscapeExe"];
// Generate the png via inkscape
ProcessStartInfo inkscapeInfo = new ProcessStartInfo(inkscape, args);
Process inkscape = Process.Start(inkscapeInfo);
inkscape.WaitForExit(5000);
runLiteral.Text = "Success!<br />" + args;
}
catch (Exception ex)
{
runLiteral.Text = ex.GetType().FullName + "<br />" + ex.Message + "<br />" + ex.StackTrace;
}
}
Can someone tell me what I'm doing wrong?
Thank you!
A couple things to check:
Make sure that the application pool identity for the web application (found in IIS, usually NetworkService) has permissions to execute inkscape.exe
If that is fine, check to make sure that the directory grants Modify permissions to the apppool identity on the directory(ies) you are writing the PNG to ("C:\inetpub\wwwroot\MyTest")
Alternatively, you can use impersonation to run the executable under a specific Windows account.

Creating SQL Server backup file (.bak) with c# to any location

I'm trying to write simple application in C# which will allow me to backup, zip and send over ftp my SQL Server database.
One problem I have encountered is that I'm not able to create the backup file (.bak) if I try to do it in different location than "C:\Program Files\Microsoft SQL Server\MSSQL.3\MSSQL\Backup" or "C:\Program Files\Microsoft SQL Server\MSSQL.3\MSSQL\Data" folder. I understand that this is a premission problem. Could someone point me to the resources or write here a short snippet how to programmatically add such a permission to any folder on my system.
Regards
Kris
i assume you are running your programm as a scheduled task ... did you give writing permissions to the target folder for the executing user of the task??
edit:
with permissions you can have 2 scenarios:
windows authenification
mixed authentification
if you are using windows authentification, the read and write permissions of the windows user are taken. otherwise the permissions for the sql server service account.
and this behaviour makes sense to me and maybe hits the nail in your scenario!
edit 2:
i don't want to encourage you to do so ... some admins may hate you when you mess up their acl's
but this may do the trick
btw: Magnus Johansson already gave you a "try-this" link
no matter for which method you go - be sure to hand in the correct user (as descriped above!)
(for full history)
...
side-note:
i know this is not the exact answer to your question, but i would recommend you smo to generate backups ...
like
using Microsoft.SqlServer.Management.Smo;
var bdi = new BackupDeviceItem(/* your path inlcuding desired file */);
var backup = new Backup
{
Database = /* name of the database */,
Initialize = true
};
backup.Devices.Add(bdi);
var server = new Server(this.SqlServer);
try
{
backup.SqlBackup(server);
}
catch (Exception ex)
{
// * log or sth
}
you only have to care for the .dll's. take assemblies for the desired server version (some params/properties vary through different server versions)
more info here
Ok Guys, Magnus and dittodhole! Thanks a lot for your help. I have combined Magnus'es link to the article on setting up permisions on the folder together with some more research and finally I've got it :).
So reassuming, I'm using Smo, and to create a folder with proper permissions I have to look for the group instead of win32_Users. Here you go a short snippet if someone finds this post he can find it usefull:
string tempPath = Directory.CreateDirectory("C:\\path_to_your_folder").FullName;
//set permissions
SelectQuery sQuery = new SelectQuery("Win32_Group",
"Domain='" +
System.Environment.UserDomainName.ToString() +
"'");
try
{
DirectoryInfo myDirectoryInfo = new DirectoryInfo("C:\\path_to_your_folder");
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);
foreach (ManagementObject mObject in mSearcher.Get())
{
string User = System.Environment.UserDomainName + "\\" + mObject["Name"];
if(User.StartsWith("your-machine-name\\SQL"))
{
myDirectorySecurity.
AddAccessRule(new FileSystemAccessRule(User,
FileSystemRights.FullControl,
AccessControlType.Allow));
}
}
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
Again thanks everyone for your help! Stackoverflow rocks!
Here is a procedure is use for back up in C#.Hope it helps
public void BackupDatabase (string BackUpLocation, string BackUpFileName, string
DatabaseName, string ServerName )
{
DatabaseName = "[" + DatabaseName + "]";
string fileUNQ = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() +"_"+ DateTime.Now.Hour.ToString()+ DateTime.Now .Minute .ToString () + "_" + DateTime .Now .Second .ToString () ;
BackUpFileName = BackUpFileName + fileUNQ + ".bak";
string SQLBackUp = #"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + BackUpLocation + #"\" + BackUpFileName + #"'";
string svr = "Server=" + ServerName + ";Database=master;Integrated Security=True";
SqlConnection cnBk = new SqlConnection(svr);
SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk);
try
{
cnBk.Open();
cmdBkUp.ExecuteNonQuery();
Label1.Text = "Done";
Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + #"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + #"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
}
finally
{
if (cnBk.State == ConnectionState.Open)
{
cnBk .Close();
}
}
}
Take a look at this article.
Remember to set the permissions for the account that the SQL Server instance is running with.
Although this may not answer your immediate question, I'd advice you to look into SQL Server Integration Services (SSIS). This looks like the exact thing SSIS was created for, and in the 2008 version there's the possibility to use C# code if needed, should the standard components not do what you need (earlier versions used VB.NET).
MSDN SSIS Info Link 1
SSIS 2005 Tutorial Link 2
Take a look at it.

Categories

Resources