I have a page where I need to display an image which is stored on the server. To find that image, I use the following code:
if (System.IO.File.Exists(Server.MapPath(filepath)))
When I use this, I get a proper result as the file is present.
But when I give an absolute path like below:
if (System.IO.File.Exists("http://myserever.address/filepath"))
It returns false.
The file is physically present there, but I don't know why it's not found.
The path parameter for the System.IO.File.Exists is the path to an actual file in the file system.
The call to Server.MapPath() changes the URI into an actual file path.
So it is working as intended.
You can't use HTTP paths in File.Exists. It supports network shares and local file systems. If you want to do this in a web application on the server side. First use Server.MapPath() first to find the physical location and then use File.Exists.
Read about Server.MapPath here: http://msdn.microsoft.com/en-us/library/ms524632%28v=vs.90%29.aspx
Eg.
string filePath = ResolveUrl("~/filepath/something.jpg");
if (File.Exists(Server.MapPath(filePath)))
{
//Do something.
}
Related
I want to save my logs to a folder which I can access with windows explorer. For example I want to create my log in the following path
This PC\Galaxy A5 (2017)\Phone\Android\data\MyApp\files
So I tried to use Environment variables... I get such as
/data/user/...
But here i cannot see the file what I created (using code I can access the path but I want to see in the explorer).
how I can create a path like above with code?
When I tried this code
var finalPath2 = Android.OS.Environment.GetExternalStoragePublicDirectory
(Android.OS.Environment.DataDirectory.AbsolutePath);
I get the path "/storage/emulated/0/data"
and
If i use the code
var logDirectory =Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.ApplicationData),"logs");
I get the following path like:
/data/user/0/MyApp/files/.config/logs
and
var logDirectory =Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.MyDocuments),"logs");
"/data/user/0/IM.OneApp.Presentation.Android/files/logs"
but unfortunately I cannot access this folder by explorer....
This PC\Galaxy A5 (2017)\Phone\Android\data\MyApp\files
So how to find out this path in c# by using environments?
Update:
when I give the following path hardcoded, it creates the file where I want..
logDirectory = "/storage/emulated/0/Android/data/MyApp/files/logs";
is there any environment to create this path? I can combine 2 environments and do some string processing in order to create this path. But maybe there is an easier way?
You are looking for the root of GetExternalFilesDir, just pass a null:
Example:
var externalAppPathNoSec = GetExternalFilesDir(string.Empty).Path;
Note: This is a Context-based instance method, you can access it via the Android application context, an Activity, etc... (see the link below to the Android Context docs)
Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using Environment.getExternalStorageState(File).
There is no security enforced with these files. For example, any application holding Manifest.permission.WRITE_EXTERNAL_STORAGE can write to these files.
re: https://developer.android.com/reference/android/content/Context#getExternalFilesDir(java.lang.String)
string docFolder = Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.MyDocuments), "logs");
string libFolder = Path.Combine(docFolder, "/storage/emulated/0/Android/data/MyApp/files/logs");
if (!Directory.Exists(libFolder))
{
Directory.CreateDirectory(libFolder);
}
string destinationDatabasePath = Path.Combine(libFolder, "temp.db3");
db.Backup( destinationDatabasePath, "main");
have a spring boot application, where I am tring to place a file inside folder of S3 target bucket. target-bucket/targetsystem-folder/file.csv
The targetsystem-folder name will differ for each file which will be retrived from yml configuration file.
The targetsystem-folder have to created via code if the folder doesnot exit and file should be placed under the folder
As I know, there is no folder concept in S3 bucket and all are stored as objects.
Have read in some documents like to place the file under folder, have to give the key-expression like targetsystem-folder/file.csv and bucket = target-bucket.
But it doesnot work out.Would like to achieve this using spring-integration-aws without using aws-sdk directly
<int-aws:s3-outbound-channel-adapter id="filesS3Mover"
channel="filesS3MoverChannel"
transfer-manager="transferManager"
bucket="${aws.s3.target.bucket}"
key-expression="headers.targetsystem-folder/headers.file_name"
command="UPLOAD">
</int-aws:s3-outbound-channel-adapter>
Can anyone guide on this issue
Your problem that the SpEL in the key-expression is wrong. Just try to start from the regular Java code and imagine how you would like to build such a value. Then you'll figure out that you are missing concatenation operation in your expression:
key-expression="headers.targetsystem-folder + '/' + headers.file_name"
Also, please, in the future provide more info about error. In most cases the stack trace is fully helpful.
In the project that I was working before, I just used the java aws sdk provided. Then in my implementation, I did something like this
private void uploadFileTos3bucket(String fileName, File file) {
s3client.putObject(new PutObjectRequest("target-bucket", "/targetsystem-folder/"+fileName, file)
.withCannedAcl(CannedAccessControlList.PublicRead));
}
I didn't create anymore configuration. It automatically creates /targetsystem-folder inside the bucket(then put the file inside of it), if it's not existing, else, put the file inside.
You can take this answer as reference, for further explanation of the subject.
There are no "sub-directories" in S3. There are buckets and there are
keys within buckets.
You can emulate traditional directories by using prefix searches. For
example, you can store the following keys in a bucket:
foo/bar1
foo/bar2
foo/bar3
blah/baz1
blah/baz2
I have a models.ImageField which I sometimes populate with the corresponding forms.ImageField. Sometimes, instead of using a form, I want to update the image field with an ajax POST. I am passing both the image filename, and the image content (base64 encoded), so that in my api view I have everything I need. But I do not really know how to do this manually, since I have always relied in form processing, which automatically populates the models.ImageField.
How can I manually populate the models.ImageField having the filename and the file contents?
EDIT
I have reached the following status:
instance.image.save(file_name, File(StringIO(data)))
instance.save()
And this is updating the file reference, using the right value configured in upload_to in the ImageField.
But it is not saving the image. I would have imagined that the first .save call would:
Generate a file name in the configured storage
Save the file contents to the selected file, including handling of any kind of storage configured for this ImageField (local FS, Amazon S3, or whatever)
Update the reference to the file in the ImageField
And the second .save would actually save the updated instance to the database.
What am I doing wrong? How can I make sure that the new image content is actually written to disk, in the automatically generated file name?
EDIT2
I have a very unsatisfactory workaround, which is working but is very limited. This illustrates the problems that using the ImageField directly would solve:
# TODO: workaround because I do not yet know how to correctly populate the ImageField
# This is very limited because:
# - only uses local filesystem (no AWS S3, ...)
# - does not provide the advance splitting provided by upload_to
local_file = os.path.join(settings.MEDIA_ROOT, file_name)
with open(local_file, 'wb') as f:
f.write(data)
instance.image = file_name
instance.save()
EDIT3
So, after some more playing around I have discovered that my first implementation is doing the right thing, but silently failing if the passed data has the wrong format (I was mistakingly passing the base64 instead of the decoded data). I'll post this as a solution
Just save the file and the instance:
instance.image.save(file_name, File(StringIO(data)))
instance.save()
No idea where the docs for this usecase are.
You can use InMemoryUploadedFile directly to save data:
file = cStringIO.StringIO(base64.b64decode(request.POST['file']))
image = InMemoryUploadedFile(file,
field_name='file',
name=request.POST['name'],
content_type="image/jpeg",
size=sys.getsizeof(file),
charset=None)
instance.image = image
instance.save()
I am developing image extraction application in .net using C# in VS2010.
i have created a path ,where the image will be extracted.But this path is specific to my system.
string image1 = "c:\\Users\\Raghu\\Desktop\\r.bmp";
I want a path which should be general i.e when the project will be deployed ,the output file should be extracted in Target Users desktop.
how create a folder on desktop and and all my extracted files goes in it.
Any ideas! please help me!!
Next code will return path to the desktop of current user:
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
So, in your case it would be
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string image1 = System.IO.Path.Combine(desktop, "r.bmp");
Environment.SpecialFolder (http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx) contains many definitions of system folder paths. Take a look which you need.
You would use the DesktopDirectory for Environment.SpecialFolder. Something like this:
public static string GetDesktopDirectory()
{
return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
}
Then using the result of that method, you can use Path.Combine to append a file name to it.
var myFilePath = Path.Combine(GetDesktopDirectory(), "r.bmp");
Path.Combine is the general solution for this, as directly concating strings may result in double slashes, etc. This takes care of that for you.
I am working on an application where I have an images folder relative to my application root. I want to be able to specify this relative path in the Properties -> Settings designer eg. "\Images\". The issue I am running into is in cases where the Environment.CurrentDirectory gets changed via an OpenFileDialog the relative path doesn't resolve to the right location. Is there a way to specifiy in the Settings file a path that will imply to always start from the application directory as opposed to the current directory? I know I can always dynamically concatenate the application path to the front of the relative path, but I would like my Settings property to be able to resolve itself.
As far as I know, there is no built-in functionality that will allow this type of path resolution. Your best option is to dynamically determine the applications executing directory and concatenate to it your images path. You don't want to use Environment.CurrentDirectory specifically for the reasons you mention - the current directory may not always be correct for this situation.
The safest code I've found to find the executing assembly location is this:
public string ExecutingAssemblyPath()
{
Assembly actualAssembly = Assembly.GetEntryAssembly();
if (this.actualAssembly == null)
{
actualAssembly = Assembly.GetCallingAssembly();
}
return actualAssembly.Location;
}
Are you looking for Application.ExecutablePath ? That should tell you where the application's executable is, remove the executable name, and then append your path to it.
2 options:
The code that uses the setting can resolve the setting against the directory of the current executing assembly.
You can create your own type that serializes as a string relative to the executing assembly, and has an accessor for the full path that will resolve against the directory of the current executing assembly.
Code sample:
string absolutePath = Settings.Default.ImagePath;
if(!Path.IsPathRooted(absolutePath))
{
string root = Assembly.GetEntryAssembly().Location;
root = Path.GetDirectoryName(root);
absolutePath = Path.Combine(root, absolutePath);
}
The nice thing about this code is that it allows a fully qualified path, or a relative path, in your settings. If you need the path to be relative to a different assembly, you can change which assembly's location you use - GetExecutingAssembly() will give you the location of the assembly with the code you're running, and GetCallingAssembly() would be good if you go with option 2.
This seem to work in both WinForms and ASP.NET (gives the path to the config file):
new System.IO.FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile).Directory;
For Windows and Console applications, the obvious way is by using:
Application.StartupPath
I suggest you to use Assembly.CodeBase, as shown below:
public static string RealAssemblyFilePath()
{
string dllPath=Assembly.GetExecutingAssembly().CodeBase.Substring(8);
return dllPath;
}
You can try Application.ExecutablePath. But you need to make reference to System.Windows.Forms. This may not be a good idea if you want your class library to steer clear of forms and UI stuff.
You can try the Assembly.GetExecutingAssembly().Location. But if, somehow, you do a "Shadow Copy" before you run your application (like the default NUnit behavior), then this property will return you the shadow copy location, not the real, physical location.
The best way is to implement a function that calls the CodeBase property of Assembly object and chop off the irrelevant portion of the string.
I use the following two methods to help with that:
public static IEnumerable<DirectoryInfo> ParentDirs(this DirectoryInfo dir) {
while (dir != null) {
yield return dir;
dir = dir.Parent;
}
}
public static DirectoryInfo FindDataDir(string relpath, Assembly assembly) {
return new FileInfo((assembly).Location)
.Directory.ParentDirs()
.Select(dir => Path.Combine(dir.FullName + #"\", relpath))
.Where(Directory.Exists)
.Select(path => new DirectoryInfo(path))
.FirstOrDefault();
}
The reason to look at parent dirs to to be easier in use during development when various build scripts end up sticking things in directories like bin\x64\Release\NonsensePath\.