I'm new to C# and would appreciate a little help.
I've a windows console application that emails logs and is scheduled to run every hour.
What I want is to zip those logs(after they have been emailed) in the same folder. ie. the folder the application is reading the logs from.
This is snipped of my code so far.
string[] files = Directory.GetFiles(#"C:\Users\*\Documents\target", "*.txt");
try
{
using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) //i'm using dotnetzip lib
{
foreach (var file in files)
{
Console.WriteLine(file);
sendEMail(file);
zip.AddFile(file,"logs");
}
zip.Save("mailedFiles.zip");
}
}
What's happening with the above code is I'm able to create a zip file but not in the same folder where the application is reading from. Instead it creates the zipfile in my program's location(which makes sense).
How do I go about changing the location of the created zipfile. Also I want the individual logs to be replaced by the one zipfile that's created.
You can save the zip file to any of the special folders available in the user folder. You can get paths for the special folders with the following line of code:
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
If you want to save the zip file other than these special folders then there might be permission issues.
Try saving it by using the directory.
For example:
{
string directory = #C:\Users*\Documents\
zip.Save(directory + "mailedFiles.zip");
}
You should also use System.IO to get the directories instead of hardcoding them.
Related
I have a byte array and need to save it to a file.
I have tried the below code:
File.WriteAllBytes("form.txt", byteArray);
string filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "form.txt");
I have referred https://stackoverflow.com/a/19455387/15265496 for the implementation.
I am looking for the file in Android emulator. Where will the file get saved from first line?
Should I create a form.txt in the application local folder?
Is there any alternative way to do the same?
You can find the appropriate folder using Environment.SpecialFolder.LocalApplicationData
string fileExactLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "form.txt");
You can find more information at https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/files?tabs=windows
You cannot access the file system of an Android emulator instance via explorer or finder.
As per the Microsoft docs, if you want to store a file in Android, you can always use the application's files folder which is accessible through:
var path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
A file saved to that folder will go to
/data/user/0/com.companyname/files
In an ASP.NET Core 2.2 app I have the ability to upload a ZIP file. The contents of the ZIP file are extracted and saved in a directory. However, before saving the files on the server, I want to check their MIME types (a.k.a. content-types) to ensure that none of them are potentially dangerous files to store, such as EXE. If the ZIP file contains an unwanted file, I'd like to just show a model error on the page.
I tried to loop through the files within the zip to check their MIME types after storing the ZIP file in the directory. With this method, while I can see the file name with extension, I can't see the MIME type. Going by the extension alone isn't a good idea because it can be spoofed.
Directory.GetFiles(directory, "*.zip", SearchOption.TopDirectoryOnly).ToList()
.ForEach(zipFilePath =>
{
using (FileStream zipToOpen = new FileStream(zipFilePath, FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
//entry does not contain MIME type, only filename with extension
}
}
}
});
Another solution would be to set the folder's permissions to deny execution, but I don't want to do that because it's something easy to forget.
Lastly, there is some way of storing files in an App_Data folder which isn't publicly available and so files in it can't be directly executed. The issue with that is I just can't find such a folder. It doesn't seem to be created automatically with my app. I'm thinking this must be a difference between ASP.NET and ASP.NET Core.
So I'm making a Tic Tac Toe application and have created a Text file linked to the program to hold the following information:
the name
the time took to win
the difficulty
I know the timer is redundant for a quick game like Tic Tac Toe but I'll use it in the future for other programs.
My question is how can I find the full path of the file while only knowing the name of the file?
I want to do this using the program so it can be transferred to any computer and still be able to access the file without the user having to input it.
The code I've tried is:
string file_name = Path.Combine(Environment.CurrentDirectory, "Tic Tac Toe\\HighScores.txt");
But this just looks in the Debug folder, where the file isn't located. The application is entirely a console application.
Try to dedicate the file in a fixed sub directory:
\TicTacToe.exe
\settings\settings.cfg
So the path is dependent of your executable file.
You'll fetch the directory by calling Directory.GetCurrentDirectory()
You can set a desired directory by setting Environment.CurrentDirectory
A common way to handle this case is the one described above.
Another would be to use user specifiy directories like the %appdata% path and create a dedicated directory there.
%appdata%\TicTacToe\settings.cfg
Everytime your application starts it should lookup the folder %appdata%\TicTacToe\
If it is present, your application has been executed with this user.
If not, just create a new one, so we know it's the first run.
You can get the %appdata% path by calling
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Example of what i would have done
private void setUp(){
string filename = "settings.cfg";
string dir = "TicTacToe";
string appdata =Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullpath = Path.Combine(Path.Combine(appdata,dir),filename);
//check if file exists, more accurate than just looking for the folder
if(File.Exists(fullpath )){
//read the file and process its content
}else{
Directory.CreateDirectory(Path.Combine(appdata,dir)); // will do nothing if directory exists, but then we have a bug: no file, but directory available
using (FileStream fs = File.Create(fullpath))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}
}
Hope it helped.
Perhaps have a configuration file for your application and store the directory name in there.
An old example from MS, but should still be applicable...
How to store and retrieve custom information from an application configuration file by using Visual C#
I'm building a Windows 8 app. This app has an item page with a list of files, and when one of these files is selected, the app should open that file.
With these analysis I started to produce code but immediately I was confronted with the difficulty to open a directory that contains a list of files in windows 8 app.
In particular I created a directory under Assets with name Report that contains the files list (pdf, txt, any kind of files).
When I need to open this directory programmatically, I'am not able to open it because I get this exception:
System.IO.FileNotFoundException
but the directory exists. I try to open it with:
var folder = await StorageFolder.GetFolderFromPathAsync(Windows.ApplicationModel.Package.Current.InstalledLocation.Path + #"\Assets\AnimalImages");
as Xyroid suggests here enter link description here but I have fix nothing.
In another attempt, I tried to access at that directory using that code:
IReadOnlyList<StorageFolder> documentsFolder = await Windows.ApplicationData.Package.Current.InstalledLocation.GetFoldersAsync();
foreach(StorageFolder folder in documentFolder){
IReadOnlyList<IStorageItem> subItems = await folder.GetItemsAsync();
foreach (IStorageItem subFolder in subItems)
{
try
{
...
}
catch(FileNotFoundException e1) { }
}
}
In this second approach, I tried to get the Assets folder (with the first loop), and I got it, and the report folder (with the second loop), that I'm not able to get it because the directory named reports does not exists.
Please, anyone of you know C# and windows 8 app better than me.
i look forward to hearing from you.
Thank you for time you reserved me.
I have a text file in Program Files. I cannot write it from a C# application while running in non-admin mode.
I am using this snippet
TextReader read = new StreamReader("C:\Program Files\......\link");
It is throwing an error that the access to the file is denied, however I can read it!
Thanks
Access to a file can be different for reading and writing. As a non-admin, it's normal to be able to read files in Program Files, but not be able to write them.
If the file is a setting for the current user, you should put it in a folder under the AppData folder. You can find the AppData folder's location by calling Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData))
If the file is a setting for all users on the computer, use Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData))
See http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx for a list of other possible special folder locations.
Non-admin users don't have write access to files in C:\Program Files by default. If you want to write to a file that is accessible to all users, you should create it in C:\ProgramData.
In .net there is a class File
through which you can use the method
File.read(file path)
this return a string
so you can easily manage it
it also works in a non admin mode