I need to read the contents of the Web.Config and send them off in an email, is there a better way to do the following:
string webConfigContents = String.Empty;
using (FileStream steam = new FileStream(
Server.MapPath("~/web.config"),
FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader reader = new StreamReader(steam))
{
webConfigContents = reader.ReadToEnd();
}
}
I dont want to lock the file. Any ideas?
Edit - I need a raw dump of the file, I cant attach the file (Webhost says nay!), and im not looking for anything specific inside it
You can replace your code with this:
string webConfigContents = File.ReadAllText(Server.MapPath("~/web.config"));
The file will be locked for writing while it is being read, but not for reading. But I don't think this will be a problem, because the web.config file is not usually being written to (since this would restart the web application).
By using the asp.net api.
System.Configuration.Configuration rootWebConfig1 =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (0 < rootWebConfig1.AppSettings.Settings.Count)
{
System.Configuration.KeyValueConfigurationElement customSetting =
rootWebConfig1.AppSettings.Settings["customsetting1"];
if (null != customSetting) {
Console.WriteLine("customsetting1 application string = \"{0}\"", customSetting.Value);
}
else {
Console.WriteLine("No customsetting1 application string");
}
}
Related
I'm writing an application in visual studio using c#. I want to check if readalltext finds the file correctly, if not it needs to create the file and put a zero in it. In pseudocode:
if(x=File.ReadAllText("file.txt")==NULL)
{
File.WriteAllText("file.txt", "0");
x=File.ReadAllText("file.txt");
}
How can I do this? Thanks in advance, I tried some google but I may be inputting the wrong keywords
You can check whether a file exists with the File.Exists() method.
string path = "file.txt";
if (!File.Exists(path))
{
File.WriteAllText(path, "0");
}
The problem with using File.Exist() is that there is a risk the file is created or deleted after the check was made. The risk may be small, but may still need to be handled. One way to handle this would be with a try/catch inside a loop:
while (true)
{
try
{
if (!File.Exists(path))
{
File.WriteAllText(path, "0");
return "0";
}
else
{
return File.ReadAllText(path);
}
}
catch (IOException)
{
// try again
}
}
Another way would be to skip ReadAllText and instead open a fileStream. If that succeeds you know you have exclusive access to the file, to either read or write to it:
try
{
using var fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
if (fs.Length == 0)
{
using var sw = new StreamWriter(fs);
sw.Write('0');
return "0";
}
else
{
using var sr = new StreamReader(fs);
return sr.ReadToEnd();
}
}
catch (Exception)
{
// Handle the various types of exception that may occur.
}
I try to create a text file and write some data to it. I am using the following code:
public void AddNews(string path,string News_Title,string New_Desc)
{
FileStream fs = null;
string fileloc = path + News_Title+".txt";
if (!File.Exists(fileloc))
{
using (fs = new FileStream(fileloc,FileMode.OpenOrCreate,FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fileloc))
{
sw.Write(New_Desc);
}
}
}
}
I got this exception in stream writer:
The process cannot access the file '..............\Pro\Content\News\AllNews\Par.txt'
because it is being used by another process.
Text file is created, but I can't write to it.
When you create your StreamWriter object, you're specifying the same file that you already opened as a FileStream.
Use the constructor overload of StreamWriter that accepts your FileStream object, instead of specifying the file again, like this:
using (StreamWriter sw = new StreamWriter(fs))
I would simply do this:
public void AddNews(string path, string News_Title, string New_Desc)
{
string fileloc = Path.Combine(path, News_Title+".txt");
if (!File.Exists(fileloc)) {
File.WriteAllText(fileloc, New_Desc);
}
}
Note that I use Path.Combine as a better way to create paths, and File.WriteAllText as a simple way of creating a file and writing something to it. As MSDN says:
If the target file already exists, it is overwritten.
so we first check if the file already exists, as you did. If you want to overwrite its contents, just don't check and write directly.
The issue could be that the file is open or in use. Consider checking if the file is open before writing to it...
public bool IsFileOpen(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
// Is Open
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//Not Open
return false;
}
Good Luck!
using (TextWriter tw = new StreamWriter(path, true))
{
tw.WriteLine("The next line!");
}
I am working on a project and I need to upload a CSV file and read it.
I am working in Visual Studio 2010 and MVC3 and C# language.
If I am to use html fileuplaod control, how I am suppose to take the uploaded file and read it in the client side itself without saving the file in the server.
Do I have to use the jquery?
I have searched but did not get solution to meet my requirements. I am new to MVC3 and CSV file handling and quite confused.
*What is the easiest way to upload a .csv file and read it in order to save it in the database.
A clear solution would be highly appreciated.Thanks.
What you can do is save the file on server, then after you read the content from them you can delete the file.
I think there is a no way you can read the from client side. You must upload it on ur server to read that.
using (StreamReader CsvReader = new StreamReader(input_file))
{
string inputLine = "";
while ((inputLine = CsvReader.ReadLine()) != null)
{
values.Add(inputLine.Trim().Replace(",", "").Replace(" ", ""));
}
CsvReader.Close();
return values;
}
You should be able to access the data without saving it - using the InputStream property
http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.inputstream.aspx
and this (see Paulius Zaliaduonis answer)
private async Task<string> ProcessAsync(string surveyId)
{ if(!Request.Content.IsMimeMultipartContent())
{
return "|UnsupportedMediaType";
}
try
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.LoadIntoBufferAsync().ConfigureAwait(false);
await Request.Content.ReadAsMultipartAsync(provider).ConfigureAwait(false);
HttpContent content = provider.Contents.FirstOrDefault();
if(content != null)
{
Stream stream = await content.ReadAsStreamAsync().ConfigureAwait(false);
using (StreamReader CsvReader = new StreamReader(stream))
{
string inputLine = "";
while ((inputLine = CsvReader.ReadLine()) != null)
{
string[] vars = inputLine.Split(',');
}
CsvReader.Close();
//return values;
}
}
}
catch(Exception e)
{
return e.ToString();
}
return "Nothing To Process";
}
I want to take a file that stored already in the isolated storage, and copy it out, somewhere on the disk.
IsolatedStorageFile.CopyFile("storedFile.txt","c:\temp")
That doesn't work. Throws IsolatedStorageException and says "Operation not permitted"
I don't see anything in the docs, other than this, which just says that "Some operations aren't permitted", but doesn't say what, exactly. My guess is that it doesn't want you copying out of isolated storage to arbitrary locations on disk. The docs do state that the destination can't be a directory, but even if you fix that, you still get the same error.
As a workaround, you can open the file, read its contents, and write them to another file like so.
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly())
{
//write sample file
using (Stream fs = new IsolatedStorageFileStream("test.txt", FileMode.Create, store))
{
StreamWriter w = new StreamWriter(fs);
w.WriteLine("test");
w.Flush();
}
//the following line will crash...
//store.CopyFile("test.txt", #"c:\test2.txt");
//open the file backup, read its contents, write them back out to
//your new file.
using (IsolatedStorageFileStream ifs = store.OpenFile("test.txt", FileMode.Open))
{
StreamReader reader = new StreamReader(ifs);
string contents = reader.ReadToEnd();
using (StreamWriter sw = new StreamWriter("nonisostorage.txt"))
{
sw.Write(contents);
}
}
}
I'm using IsolatedStorage in a Silverlight application for caching, so I need to know if the file exists or not which I do with the following method.
I couldn't find a FileExists method for IsolatedStorage so I'm just catching the exception, but it seems to be a quite general exception, I'm concerned it will catch more than if the file doesn't exist.
Is there a better way to find out if a file exists in IsolatedStorage than this:
public static string LoadTextFromIsolatedStorageFile(string fileName)
{
string text = String.Empty;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName,
FileMode.Open, isf))
{
using (StreamReader sr = new StreamReader(isfs))
{
string lineOfData = String.Empty;
while ((lineOfData = sr.ReadLine()) != null)
text += lineOfData;
}
}
return text;
}
catch (IsolatedStorageException ex)
{
return "";
}
}
}
From the "manual" (.net framework 2.0 Application Development Foundation):
Unlike the application programming interface (API) for files stored arbitrarily
in the file system, the API for files in Isolated Storage does not support checking
for the existence of a file directly like File.Exists does. Instead, you need to ask the
store for a list of files that match a particular file mask. If it is found, you can open the
file, as shown in this example
string[] files = userStore.GetFileNames("UserSettings.set");
if (files.Length == 0)
{
Console.WriteLine("File not found");
}
else
{
// ...
}