I created a android app to create a stockage list by capturing code bars, the idea is to write a csv file in to a network folder, because I want the app to run as much offline as it's possible.
Currently my code looks like:
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
string filename = Path.Combine(path, "stock.csv");
using (var streamWriter = new StreamWriter(filename, true))
using (var writer = new CsvWriter(streamWriter))
{
foreach (var item in articulos)
{
writer.WriteField(item.codbar);
writer.WriteField(item.reference);
writer.WriteField(item.quantity);
writer.NextRecord();
}
}
string path2 = #"\\Desktop-jce8pl5\csv\stock.csv";
File.Copy(filename, path2,true);
But I keep geting a System.UnauthorizedAccessException
I tried to enter directly to the file from another computer and there
is no problem.
I give full permission to "all" and "network"
I tried directly with IP I tried not to copy, just to create
string path = #"\\Desktop-jce8pl5\csv\stock.csv";
FileStream fs = null;
if (File.Exists(path))
{
fs = File.Open(path, FileMode.Append);
}
else
{
fs = File.Create(path);
}
But there is no way.
Any help?
Thanks.
As #RobertN sugested, I tried to connect with EX File Ex and detected that I was unable to, so I checked the windows 10 general configuration to shared folders and it was only enabled to auth users.
I changed that, then I start with the cifsmanager but on that moment we decided that, if the user has access to local network he will most sure have acces to internet, so I will send the file by email.
Related
As the title says, if I open Visual Studio IDE as Admin, FileStream works just fine. But if I don't run as admin, it gives Access to the path 'C:\\ABCD.ddthp' is denied. But if I select a folder inside the C directory it works fine. For example if the path is 'C:\ABCFolder\ABCD.ddthp' it works fine. Here is my code. Is there any work around for this or should the IDE be opened as Admin.
try
{
if (File.Exists(path))
{
File.Delete(path);
}
//The following line causes an exception.
using (var stream = new FileStream(path,
FileMode.CreateNew, FileAccess.Write).Encrypt())
{
using (StreamWriter streamWriter = new StreamWriter(stream))
{
JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter);
jsonWriter.Formatting = Formatting.Indented;
protocolJObject.WriteTo(jsonWriter);
}
}
return ReturnCodes.Success;
}
catch (UnauthorizedAccessException ex)
{
SystemDebugLogLogger.LogError(ex, "Protocol: WriteJson");
returnValue = ReturnCodes.FileAccessDenied;
}
The workaround would be to not write directly to the C: drive, or any other location that requires administrative access. Depending on the purpose of the file, there are usually three candidate locations:
The temp folder, for files that you don't need to save
The AppData folder, for files that your application will need and which may be different for different users
The install location for your application
You can get these folders like:
private static void Main()
{
// Create your own file name
var fileName = "MyAppData.txt";
// Get temp path
var tempPath = Path.GetTempPath();
// Get AppData path and add a directory for your .exe
// To use Assembly.GetExecutingAssembly, you need to add: using System.Reflection
var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var exeName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
var appDataForThisExe = Path.Combine(appDataFolder, exeName);
Directory.CreateDirectory(appDataForThisExe);
// Get the path where this .exe lives
var exePath = Path.GetDirectoryName(
new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
// Now you can join your file name with one of the above paths
// to construct the full path to the file you want to write
var tempFile = Path.Combine(tempPath, fileName);
var appDatFile = Path.Combine(appDataForThisExe, fileName);
var exePathFile = Path.Combine(exePath, fileName);
Console.WriteLine($"Temp file path:\n {tempFile}\n");
Console.WriteLine($"AppData file path:\n {appDatFile}\n");
Console.WriteLine($"Exe location file path:\n {exePathFile}");
Console.WriteLine("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output
Your user account doesn't have permission to write to the C:\ drive of your computer but admin does.
You can give yourself permission by right clicking on the C:\ drive in windows explorer, select properties and then the security tab and give your account write access.
Alternatively, use a better location
I'm working with DocumentFormat.OpenXml.SpreadsheetDocument and opening a template of an Excel document, writing to it and saving it.
It works like charm from a normal File stream:
using (var documentStream = System.IO.File.Open("--somePath--", FileMode.Open, FileAccess.ReadWrite))
{
using (var document = SpreadsheetDocument.Open(documentStream, true))
{
// do something
}
}
Notice the SpreadsheetDocument.Open
Now, I'm rewriting this application to Azure, and using Azure storage and it's .NET File library in "WindowsAzure.Storage" package.
It works like a charm, all up to a point where I want to fill the same excel files in Azure.
using (var documentStream = _GetRootDirectoryOfAccount().GetFileReference("--someRelativePath--").OpenWrite(null))
{
using (var document = SpreadsheetDocument.Open(documentStream, true))
{
// do something
}
}
The first part "_GetRootDirectoryOfAccount().GetFileReference" works 100%, then OpenWrite(null) really opens a Stream.
However, when that Stream is pushed towards the Spreadsheet:
SpreadsheetDocument.Open(documentStream, true)
It breaks with:
System.IO.IOException: 'Cannot open package because FileMode or
FileAccess value is not valid for the stream.'
And it is because on the Stream the settings are not set:
System.IO.File.Open("--somePath--", FileMode.Open, FileAccess.ReadWrite)
Does anyone know how to get around this? Or a solution?
Please :)
Does anyone know how to get around this? Or a solution?
The return type of _GetRootDirectoryOfAccount().GetFileReference("--someRelativePath--").OpenWrite(null)) is CloudFileStream
`
It seems that CloudFileStream is not supported by SpreadsheetDocument.Open().
Please have a try to use the following code,it works correctly on my side. After update the content, we could use file.UploadFromFile() or file.UploadFromStream() to upload the file.;
var file = _GetRootDirectoryOfAccount().GetFileReference("--someRelativePath--");
var memoryStream = new MemoryStream();
file.DownloadToStream(memoryStream);
using (var document = SpreadsheetDocument.Open(memoryStream, true))
{
// do something
}
The following is my demo code.
var connectionString = "DefaultEndpointsProtocol=https;AccountName=accountName;AccountKey=xxxxx;EndpointSuffix=core.windows.net";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
// Get a reference to the file share we created previously.
CloudFileShare share = fileClient.GetShareReference("test"); //share name
if (share.Exists())
{
// Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.GetRootDirectoryReference();
// Get a reference to the directory we created previously.
CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("custom");
// Ensure that the directory exists.
if (sampleDir.Exists())
{
// Get a reference to the file we created previously.
var file = sampleDir.GetFileReference("OpenXMl.xlsx"); //file name
// Ensure that the file exists.
if (file.Exists())
{
// Write the contents of the file to the console window.
Console.WriteLine(file.DownloadTextAsync().Result);
var memoryStream = new MemoryStream();
file.DownloadToStream(memoryStream);
using (var document = SpreadsheetDocument.Open(memoryStream, true))
{
// do something
}
}
}
}
I'm using Xamarin, and according to previous answers, this shall work:
string path = Path.Combine(Android.OS.Environment.DirectoryDownloads, "families.txt");
File.WriteAllText(path, "Write this text into a file!");
But it doesn't, I get and unhandled exception. I have set the permissions to read and write to external storage (even though this is internal).
I also tried it with this:
string content;
using (var streamReader = new StreamReader(#"file://" + path )) // with and without file://
{
content = streamReader.ReadToEnd();
}
But I got the same unhandled exception.
UPDATE: The path is the problem, since I get the else part here:
Java.IO.File file = new Java.IO.File(path);
if (file.CanRead())
testText.Text = "The file is there";
else
testText.Text = "The file is NOT there\n" + path;
Which is weird, because the path seems to be correct. The exceptions: Could not find a part of the path: /Download/families.txt
UPDATE2: On external storage, it works, with the same code... Might it be my device's problem? That would be great, cause I tested the external storage version on my friend's phone, but mine doesn't have external storage (OnePlus One), so I'm still looking for a solution (if there's any).
Finally found a solution.
var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filename = Path.Combine(path.ToString(), "myfile.txt");
The path was the problem, now with a simple streamwriter it works like magic.
try
{
using (var streamWriter = new StreamWriter(filename, true))
{
streamWriter.WriteLine("I am working!");
}
}
catch { ... }
i wish to write to a protected text file note this content is important.
Can i write to a file to keep it protected i am going to use encryption
but do not wish anyone to read the content of the file. I have tried to
use File.WriteText? but the problem is that the file gets written then
unused so anyone can read the content.
Protection eg. Like the SAM file
In Microsoft Dotnet framework, TextFile attributes are available in c# will enable you to keep the file encrypted and readonly. The write protection can be done using FileIOPermissionAccesss If current user is administrator then he will able to give protect and delete permissions for particular can be given to the file. Below is sample code for adding permission.
var permissionSet = new PermissionSet(PermissionState.None);
var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
permissionSet.AddPermission(writePermission);
if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
{
using (FileStream fstream = new FileStream(filename, FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
// try catch block for write permissions
writer.WriteLine("sometext");
}
}
else
{
//perform some recovery action here
}
I too faced similar problem, instead in my case the problem was the
data in my file should be visible to anyone even to the admin user,
and for every time the application runs the previous data should be
replaced by the new one.
Here's my code
string pathfile = #"C:\Users\Public\Documents\Filepath.txt";
if (File.Exists(pathfile))
{
File.Delete(pathfile);
}
if (!File.Exists(pathfile))
{
using (FileStream fs = File.Create(pathfile))
{
Byte[] info = new UTF8Encoding(true).GetBytes("Your Text Here");
fs.Write(info, 0, info.Length);
FileSecurity fsec = File.GetAccessControl(pathfile);
fsec.AddAccessRule(new FileSystemAccessRule("Everyone",
FileSystemRights.FullControl, AccessControlType.Deny));
File.SetAccessControl(pathfile, fsec);
}
}
I have a service that reads an xml document from a directory(works OK), saves the data in sql (works OK) and after that I am copying the file to a FINISHED directory (works OK) and deleting the file (NOT working)from the reading directory. The PROBLEM that I have is that the file is being locked when I try to execute the DELETE. Any advise will be appreciated so I can find where the file is being locked.
static public Res GetResMn(string FileName)
XDocument root = null;
using (var file = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader oReader = new StreamReader(file, Encoding.GetEncoding("ISO-8859-1")))
{
root = XDocument.Load(oReader);
oReader.Close();
oReader.Dispose();
}
Here is the code for the copy and delete
void CopyFile(string FileToMove, string MoveLocation)
{
try
{
System.IO.File.Copy(FileToMove, MoveLocation, true);
//System.IO.File.Move(FileToMove, MoveLocation);
File.Delete(FileToMove);
}
catch (Exception e)
{
WriteLogFile("The process failed: {0} " + e.ToString());
}
}
This is the code when I get the values from the file
var myElement1 = root.Descendants(XName.Get("rnID", #"namespace.2.0")).FirstOrDefault();
if (myElement1 != null)
{
myRPr.rnID = root.Descendants(XName.Get("rnID", #"namespace.2.0")).FirstOrDefault().Value;
}
This is the error that I am getting in my logFile
{0} System.UnauthorizedAccessException: Access to the path 'C:\ReadingDirectory\FileName.xml' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.Delete(String path)
at OperaWinSrvc.OperaWinSrvc.ReadFiles()
I am gettign the same kind of error when I tried the
System.IO.File.Move
Be sure you are calling .Close() on the file object prior to attempting a delete and that you have security permissions to delete from that folder as well.
Access Denied is usually a permissions problem, but can occasionally be caused by a file locking condition.
After doing multiple check ups in different places I finally found the solution to my problem. In the service installer I had the Account property set to Local Service, I change it to LocalSystem, reinstall the service and it appears to work now.