The specified network name is no longer available - C# Console Application - c#

I am trying to read files from different server, using c# console application, but it gives error - "The specified network name is no longer available".
When I ping the server, i am getting a reply, but when I run the exe file of project that has code to access files from server it shows the mentioned error.
The path I am using is in this format: \\xxx.xxx.xx.x\EEE\EEE\FolderName
The code that access/read files:
public List<string> GetFiles()
{
List<string> filelist = null;
string fileFromPath = help.fileFromPath;
try
{
filelist = Directory.GetFiles(fileFromPath).ToList();
if (filelist.Count == 0)
{
log.Error("No file to be processed.");
}
}
catch (Exception ex)
{
log.Error(ex.Message);
}
return filelist;
}
Where help.fileFromPath has path value and it is stored in app.config
What could be the reason and how could it be fixed?

Related

Does the Directory class object cache information?

I was under the impression that the Directory class methods GetDirectories() and Exists() always get the current situation in a directory. But somehow that seems not to be true for file shares.
I'm repairing a complex background service that automatically copies files from a local directory to a share. Everything works just fine a long as I don't touch the files in the share.
For some reason when I delete files in the destination share the GetDirectories() and Exist() tell the service they are already there but they aren't.
The code below is a recursive routine that creates the destination directories in the same order as the source. But sometimes is just doesn't. I've tested the regular expressions which determine certain conditions and come to the conclusion that they work as expected so one of the .Success properties is correctly true. That's not where it is failing. The path does not contian the 'Quant....' strings either. So it should always create the directories.
I've tried to reproduce this locally but can't. It only happens on the production server after files have been deleted from the destination share.
The only conclusion I Can come up with is that the directory information for the share is cached somewhere. If I stop the service, delete the files and start the service again. Everything works perfectly. If I delete the files while service is running it crashes during copy with this exception:
Could not find a part of the path
'\\wur\dfs-root\PROJECTS\ESG_ERA_GLP\D0154234\1\NONGLP\2020\cpf\2020.okt26\cpf001.d\AcqData-CumulativeAuditTrail.xml'.
because part of the directorystructure was not created. If I look in the destination the directory starting with '2020.okt26' has not been created.
private void CreateFolders(string sourcePath, string destinationPath)
{
foreach (string dirPath in Directory.GetDirectories(sourcePath))
{
try
{
var destFolder = (destinationPath + dirPath.Remove(0, _sourceRootFolder.Length));
if (!destFolder.HasRootLocks(destinationPath))
{
Match isGlpFolder = glpFolders.Match(dirPath);
Match isNonGLPFolder = nonglpFolders.Match(dirPath);
Match isNonGLPRootFolder = destNonglpRootFolders.Match(destFolder);
Match isGLPRootFolder = destGlpRootFolders.Match(destFolder);
destFolder = (destinationPath + dirPath.Remove(0, _sourceRootFolder.Length));
if ((isGlpFolder.Success || isNonGLPFolder.Success)
&& !dirPath.Contains("QuantResults")
&& !dirPath.Contains("QuantReports"))
{
if (!Directory.Exists(destFolder))
{
var di = Directory.CreateDirectory(destFolder);
if (isGLPRootFolder.Success)
{
SetDirSec(destFolder, glpAccessRule, true);
}
if (isNonGLPRootFolder.Success)
{
SetDirSec(destFolder, nonglpAccessRule, true);
}
}
Match isQuantFolder = quantFolders.Match(destFolder);
if (isGlpFolder.Success && isQuantFolder.Success)
{
Directory.CreateDirectory($"{destFolder}\\QuantResults");
Directory.CreateDirectory($"{destFolder}\\QuantReports");
}
}
#if EXTRAINFO
else
{
Log.Info($"Did not create folder: {destFolder} GLP?:{isGlpFolder.Success} NONGLP?:{isNonGLPFolder.Success}");
}
#endif
}
CreateFolders(dirPath, destinationPath);
}
catch (UnauthorizedAccessException ex)
{
_glpDebugger.DebugMessage($"Fout bij folder {dirPath}. Error: {ex.Message}", true, true, false);
Log.Info($"CreateFolders: {ex.MessageEx()}");
continue;
}
catch (Exception ex)
{
_glpDebugger.DebugMessage($"Fout bij folder {dirPath}. Error: {ex.Message}", true, true, false);
Log.Info($"CreateFolders: {ex.MessageEx()}");
continue;
}
finally
{
//continue on error
}
}
}

Read files from LAN folder using StorageFolder.GetFilesAsync returns folders but no files

I'm trying to write a basic UWP app to stream media over a LAN via DLNA. I have three PC's on the same LAN, all running W10 Pro, a Homegroup set up, Media streaming switched on and configured on all of them but when I run the method below, passing in a remote folder all I get in folders back and no files, even though I know the folders contain files.
async private void LoadMediaFiles(StorageFolder mediaServerFolder)
{
try
{
MediaFolders = await mediaServerFolder.GetFoldersAsync();
MediaList.Items.Clear();
if (MediaFolders.Count > 0)
{
MediaList.Items.Clear();
foreach (StorageFolder folder in MediaFolders)
{
MediaList.Items.Add(" + " + folder.DisplayName);
}
MediaTitle.Text = "Media folders retrieved";
}
var queryOptions = new QueryOptions();
var options = new QueryOptions();
options.FileTypeFilter.Add(".avi");
options.FileTypeFilter.Add(".mp4");
options.FileTypeFilter.Add(".mkv");
options.FileTypeFilter.Add(".wmv");
options.FolderDepth = FolderDepth.Deep;
var queryFolder = mediaServerFolder.CreateFileQueryWithOptions(queryOptions);
MediaFiles = await queryFolder.GetFilesAsync();
if (MediaFiles.Count > 0)
{
foreach (StorageFile file in MediaFiles)
{
MediaList.Items.Add(file.DisplayName);
}
MediaTitle.Text = "Media files retrieved";
}
else
MediaTitle.Text = "No files found";
}
catch (Exception ex)
{
MediaTitle.Text = "Error locating media files " + ex.Message;
}
}
To get the known DLNA servers I use:
IReadOnlyList<StorageFolder> MediaServers = await KnownFolders.MediaServerDevices.GetFoldersAsync();
and then list the folders from the selected server. When the user taps on any folder it calls the above method but I never get files, only folders.
I can stream between each of the PC's no problem using WMP or VLC etc, it's only trying to get media files via UWP to stream that it doesn't work... I just get "No files found" on every folder.

How to send a local file through a REST service?

I am developing a REST web service using WCF and C# (VS 2010). I want to develop an operation like this:
doSomethingWithAFile(String filePath)
so it would be invoked like this:
GET http://my.web.service/endpoint?filePath={filePath}
filePath is a file path in the client (not in the server). So, when invoked, that operation has to send the file pointed by the path to the server so that the server can do some operations with the data contained in the file.
How can I achieve this?
EDIT: As stated in the comment I made, I would set a shared folder in the client, so I send the path and the server reads the file in the folder.
On your server, you will have to have a service with a method that accepts a string input, which you call with the file path from the client application.
You then read/copy/whichever the file from that location, on your server via normal file IO methods.
An example of how to do this you can find below.
The definition of ServerPleaseFetchThisFile naturally depends on what kind of webservice this would be, WCF or IIS web service or self made web service.
public bool ServerPleaseFetchThisFile(string targetPath)
{
// targetPath should enter from the client in format of \\Hostname\Path\to\the\file.txt
return DoSomethingWithAFile(targetPath);
}
private bool DoSomethingWithAFile(string targetFile)
{
bool success = false;
if (string.IsNullOrWhiteSpace(targetFile))
{
throw new ArgumentNullException("targetFile", "The supplied target file is not a valid input.");
}
if (!File.Exists(targetFile))
{
throw new ArgumentNullException("targetFile", "The supplied target file is not a valid file location.");
}
try
{
using (FileStream targetStream = new FileStream(targetFile, FileMode.Open, FileAccess.Read))
{
// Do something with targetStream
success = true;
}
}
catch (SecurityException se)
{
throw new Exception("Security Exception!", se);
// Do something due to indicate Security Exception to the file
// success = false;
}
catch (UnauthorizedAccessException uae)
{
throw new Exception("Unathorized Access!", uae);
// Do something due to indicate Unauthorized Access to the file
// success = false;
}
return success;
}

Upload to FTP server C# using Tamir.SharpSSH

Im able to connect with my sftp server and I'm sure of it because I get the list of files of my server and it passes correct list. But I cant upload file to a folder in mysftp server. Here is my code:
private static void FileUploadUsingSftp(string SFTPAddress, string SFTPUserName, string SFTPPassword,
string SFTPFilePath, string FileName)
{
Sftp sftp = null;
try
{
sftp = new Sftp( SFTPAddress,SFTPUserName , SFTPPassword);
// Connect Sftp
sftp.Connect();
MessageBox.Show("Connected!");
//Check if im surely connected
//list down files in my sftp server folder u01
ArrayList list;
list = sftp.GetFileList("//u01");
foreach (string item in list)
{
MessageBox.Show(item.ToString());
}
MessageBox.Show(list.Count.ToString());
// upload file
sftp.Put(FileName, "//u01"); -----> **I get exception here**
MessageBox.Show("UPLOADED!");
// Close the Sftp connection
sftp.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
if (sftp != null)
{
sftp.Close();
}
}
}
I recieve this exception:
"Exception of type 'Tamir.SharpSsh.jsch.SftpException' was thrown."
at Tamir.SharpSsh.jsch.ChannelSftp.put(String src, String dst, SftpProgressMonitormonitor, Int32 mode)
at Tamir.SharpSsh.Sftp.Put(String fromFilePath, String toFilePath)
I've tried using sftp.Put(FileName,SFTPAddress + "//u01");
Ive tried sftp.Put(FileName,SFTPAddress); And it do work but when I look at my sftp server if the file is there, it isn't.
I've tried sftp.Put(FileName,"//u01"); and it throws the same error.
I must upload my file in a folder in my ftp server and one of the folder is u01.
Can anyone help me out. I don't know what's wrong. I'm sure that i'm connected. and when I tried to upload using filezilla it do work so I'm not restricted in writing to our sftp server.
I believe that you have to enter the full filename in your call to Put.
string strippedFileName = StripPathComponent(FileName);
sftp.Put(FileName,"//u01//" + strippedFileName);
Note that StripPathComponent is not implemented, you will have to implement that as well if needed. It would strip a path component from FileName, i.e. remove C:\...\ or ..\...\.
I was also searching for how to upload a file from local/shared path to SFTP server using this library and finally found the solution. You can use the below code.
string host="ssgty";
string username="usr";
string password="passw";
int port=22;
string fromFile=#"D:\Test.txt";
string toFile=#"/dmon/myfolder/Test.txt";
public string CopyToFTP(string host, string username, string password, int port, string fromFile, string toFile)
{
string error = "";
try
{
Scp scp = new Scp(host, username, password);
scp.Connect(port);
scp.To(fromFile, toFile);
}
catch (Exception ex)
{
error = ex.Message;
}
return error;
}

The remote server returned an error: (405) Method Allowed

I know that this is a common problem facing over, but am getting this this problem with a different scenario.
am going to explain scenario here
I created a two different projects in a solution. The image containing folder that i want to use for save, i-e upload is outside of these above projects but under same solution.
Actually i created virtual directly (My File Server) on IIS server of this folder
here is my code.
private void SaveData()
{
string filename = Path.GetFileName(ImageUpload.PostedFile.FileName);
string servpath = Server.MapPath(ConfigurationManager.AppSettings["TempFolder"]);
ImageUpload.SaveAs(servpath + filename);
string remoteServerPath = ConfigurationManager.AppSettings["ProductImagesPath"] + filename;
try
{
WebClient client = new WebClient();
client.UploadFile(remoteServerPath, servpath + filename);
}
catch (Exception ex)
{
throw ex;
}
objProductsCustom.ProductName = txtProductName.Text;
objProductsCustom.ProductDiscription = txtAddDiscription.Text;
objProductsCustom.ProductPrice = txtPrice.Text;
objProductsCustom.Quantity = txtQuantity.Text;
objProductsCustom.ImagePath = "servpath" + filename;
int productID = objProductsManager.CreatProduct(objProductsCustom);
}
Where on try-catch, I found "The remote server returned an error: (405) Method Allowed." error. I am stuck.
EDIT
This is the remoteserverpath :
http://localhost/ProductImages/untitled.bmp
And this is the file which i am uploading to remoteserverpath:
C:\Documents and Settings\saltaf\My Documents\Visual Studio 2010\Projects \OnlineShoppingSystem\OnlineShoppingSiteAdminPanel\Temp\Images\untitled.bmp
And this is my call:
webclient.UploadFile(http://localhost/ProductImages/untitled.bmp,C:\Documents and Settings\saltaf\My Documents\Visual Studio 2010\Projects\OnlineShoppingSystem\OnlineShoppingSiteAdminPanel\Temp\Images\untitled.bmp)
Have you tried checking the permissions for the folder which you are saving the file into? It's supposed to include the 'IIS_IUSRS' profile there (which should also have the WRITE permission to the target folder).
Hope this helps.

Categories